滑动UITableView进行编辑

时间:2018-10-24 16:41:47

标签: ios swift uitableview segue swipe

我有两个uitableviewcontroller,一个是列表表,另一个是编辑表。 我使用附件动作来编辑项目。效果很好。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if  segue.identifier == "EditItem" {
        let controller = segue.destination as! ItemDetailViewController
        controller.delegate = self
        if let indexPath = tableView.indexPath(for: sender as! UITableViewCell) {

            controller.itemToEdit = items[indexPath.row]
        }
    }
}

现在我添加了滑动功能来编辑项目

override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {

    let edit = UIContextualAction(style: .normal, title: "Edit") { action, view, completion in
        self.performSegue(withIdentifier: "EditItem", sender: self)

        completion(true)
    }

    let delete = UIContextualAction(style: .destructive, title: "Delete") { [weak self] action, view, completion in
        self?.items.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: UITableView.RowAnimation.automatic)
        self?.saveChannelListItems()
        completion(true)
    }

    edit.backgroundColor = .purple
    edit.image = #imageLiteral(resourceName: "edit")
    delete.backgroundColor = .red
    delete.image = #imageLiteral(resourceName: "delete")


    return UISwipeActionsConfiguration(actions: [delete, edit])
}

那我有错误。

  

无法将类型'abc.ListController'(0x1089b1398)的值强制转换为'UITableViewCell'(0x1150f18e0)。

如何滑动以编辑项目?

1 个答案:

答案 0 :(得分:0)

您在此处发送self参数中的vc的sender

self.performSegue(withIdentifier: "EditItem", sender: self)

并强行将其解包到单元中

if let indexPath = tableView.indexPath(for: sender as! UITableViewCell) {

相反,您可以这样做

self.performSegue(withIdentifier: "EditItem", sender:items[indexPath.row])

使用

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if  segue.identifier == "EditItem" {
         let controller = segue.destination as! ItemDetailViewController
         controller.delegate = self 
         controller.itemToEdit = sender as! ItemType // where ItemType is the type of the array elements 
        }
    }
}