Thursday, December 29, 2016

Swipe Actions for UITableViewCell

There are two references Ref[1,2] on swipe actions for UITableViewCell. Things have changed a bit for iOS 8.2.

For example, the following function is not needed for UITableView's delegate to make rows editable. By default, the rows are editable.
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }

To disable rows from editing, we can return false for the above function.

Ref[2] illustrates how to delete a row. For Xcode 8.2, the corresponding code snippet is below
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == UITableViewCellEditingStyle.delete {
            todoList.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
        }
    }

We can also use editActionsForRowAt to delete a row as below.

    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        let delAction = UITableViewRowAction(style: UITableViewRowActionStyle.default, title: "Delete") { (action, index) in
            self.todoList.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
        }
        delAction.backgroundColor = UIColor.orange
        return [delAction]
    }

editActionsForRowAt can enable more actions for a row and is more useful.


References
--------------
1. http://www.brianjcoleman.com/tutorial-swipe-actions-for-uitableviewcell-in-swift/
2. https://www.ioscreator.com/tutorials/delete-rows-table-view-ios8-swift

1 comment:

  1. Not working in iOS 9 with Swift 3!! The editActionsForRowAt is not working !!!

    ReplyDelete