How to enable swipe to delete cell in a TableView?

后端 未结 13 2623
悲哀的现实
悲哀的现实 2020-12-07 21:40

I have a UIViewController that implements TableViews delegate and datasource protocols. Now I want to add \"swipe to delete\" gesture to cells.

13条回答
  •  失恋的感觉
    2020-12-07 22:40

    Please try this code in swift,

    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
       // let the controller to know that able to edit tableView's row 
       return true
    }
    
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)  {
       // if you want to apply with iOS 8 or earlier version you must add this function too. (just left in blank code)
    }
    
    override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]?  {
       // add the action button you want to show when swiping on tableView's cell , in this case add the delete button.
       let deleteAction = UITableViewRowAction(style: .Default, title: "Delete", handler: { (action , indexPath) -> Void in
    
       // Your delete code here.....
       .........
       .........
       })
    
       // You can set its properties like normal button
       deleteAction.backgroundColor = UIColor.redColor()
    
       return [deleteAction]
    }
    

提交回复
热议问题