Add swipe to delete UITableViewCell

后端 未结 25 1636
暖寄归人
暖寄归人 2020-11-30 17:50

I am making a CheckList application with a UITableView. I was wondering how to add a swipe to delete a UITableViewCell.

This is my ViewCont

25条回答
  •  旧时难觅i
    2020-11-30 18:17

    Xcode asks for UIContextualAction, here what worked for me for the updated version:

    For Trailing Swipe Actions:->

     func delete(forRowAtIndexPath indexPath: IndexPath) -> UIContextualAction {
            let company = companies[indexPath.row]
            let action = UIContextualAction(style: .destructive, title: "Delete") { (action, view, _) in
               // Perform Delete Action
            }
            return action
        }
        
        func edit(forRowAtIndexPath indexPath: IndexPath) -> UIContextualAction {
            let action  = UIContextualAction(style: .normal, title: "Edit") { (action, view, escaping) in
                // Perform Edit Action
            }
            return action
        }
        
        override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
            let delete = self.delete(forRowAtIndexPath: indexPath)
            let edit = self.edit(forRowAtIndexPath: indexPath)
            let swipe = UISwipeActionsConfiguration(actions: [delete, edit])
            return swipe
        }
    

    For Leading Swipe Actions:->

     func delete(forRowAtIndexPath indexPath: IndexPath) -> UIContextualAction {
            let company = companies[indexPath.row]
            let action = UIContextualAction(style: .destructive, title: "Delete") { (action, view, _) in
               // Perform Delete Action
            }
            return action
        }
        
        func edit(forRowAtIndexPath indexPath: IndexPath) -> UIContextualAction {
            let action  = UIContextualAction(style: .normal, title: "Edit") { (action, view, escaping) in
                // Perform Edit Action
            }
            return action
        }
        
        override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
            let delete = self.delete(forRowAtIndexPath: indexPath)
            let edit = self.edit(forRowAtIndexPath: indexPath)
            let swipe = UISwipeActionsConfiguration(actions: [delete, edit])
            return swipe
        }
    

    Return true for canEditRowAt for tableView Delegate:->

    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
            return true
        }
    

提交回复
热议问题