复制所选单元格中的数据(Swift)

问题描述 投票:3回答:2

我在UITableViewCellю中左/右滑动

我该如何制作它以便我可以从所选单元格中复制数据?

我试着用它:

let cell = self.table.cellForRow(at: indexPath)
UIPasteboard.general.string = cell?.detailTextLabel?.text

但应用程序崩溃了

enter image description here

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell")!
    cell.textLabel?.text = myData[indexPath.row]
    return cell
}

func tableView(_ tableView: UITableView,leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?{
    let closeAction = UIContextualAction(style: .normal, title:  "Close", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
        print("Copy")

            //let cell = self.table.cellForRow(at: indexPath)
            //UIPasteboard.general.string = cell?.detailTextLabel?.text

        success(true)
    })
    closeAction.title = "Copy"
    closeAction.backgroundColor = .purple

    return UISwipeActionsConfiguration(actions: [closeAction])
}
ios swift xcode uitableview copy
2个回答
5
投票

更换:

let cell = self.table.cellForRow(at: indexPath)
UIPasteboard.general.string = cell?.detailTextLabel?.text

附:

let cell = tableView.cellForRow(at: indexPath)
UIPasteboard.general.string = cell?.textLabel?.text

因为你在tableView方法中使用cellForRowAt。所以我用table替换tableView,在第二行用detailTextLabel替换textLabel

这应该工作。


1
投票

您可以使用数据数组中的字符串,如下所示:

UIPasteboard.general.string = myData[indexPath.row]

而不是这个:

let cell = self.table.cellForRow(at: indexPath)
UIPasteboard.general.string = cell?.detailTextLabel?.text
© www.soinside.com 2019 - 2024. All rights reserved.