Saturday, November 26, 2016

Swift 3 UITableView editing and row actions

In this post let’s see how to add Delete/Update buttons on row actions on UITableView rows.


Add below table view delegates along with your remaining tableview delegate methods.

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


       
  
    func tableView(_ tableView: UITableView, editActionsForRowAt 
                                indexPath: IndexPath) -> [UITableViewRowAction]?
    {
        let update = UITableViewRowAction(style: .normal, title: "Update") 
                                                                                         { action, index in
        }
        update.backgroundColor = UIColor.darkGray
        
        let delete = UITableViewRowAction(style: .default, title: "Delete") 
                                                                                         { action, index in
            self.arrContent.remove(at: indexPath.row)
            self.tableView.reloadData()
        }
        return [delete, update]
    }

   }


     
If you look at the above code, we are allowing the row edit in the ‘canEditRowAt’ delegate method.

In the ‘editActionsForRowAt’ delegate method, We can add button styles, actions and customise many more.

Finally, the buttons will appear when you swipe left on the row in the order we have given in the return UITableViewRowAction array.

 return [delete, update]

Hope this post is useful. Feel free to comment incase of any queries.