I am using a the swipe to delete feature in the tableview to delete selected cells. You swipe it to the left to reveal a delete button. My code works well and deletes like it should.
I am also including a UIAlertController to give the user of the app a single last chance from making a mistake. What I would like to do is if the user selects "Cancel" is have the cell "un-swipe" and return to its original position. Is there a way to do this?
You can turn off editing on the tableView
[self.tableView setEditing:NO animated:YES];
I came across this question trying to do the same thing. I thought there had to be a better solution that reloading the table, so I did some further research and found the following.
tableView.setEditing(false, animated: true)
here's a little more code (Swift 3) to show it in use
// Custom cell edit actions
func tableView(_ tableView: UITableView, editActionsForRowAt: IndexPath) -> [UITableViewRowAction]? {
let delete = UITableViewRowAction(style: .destructive, title: "Delete") {(rowAction: UITableViewRowAction, indexPath: IndexPath) -> Void in
let refreshAlert = UIAlertController(title: "Delete", message: "Are you sure you want to delete this item.", preferredStyle: UIAlertControllerStyle.alert)
refreshAlert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (action: UIAlertAction!) in
let context = self.fetchedResultsController.managedObjectContext
context.delete(self.fetchedResultsController.object(at: indexPath))
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}))
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
// if the user presses cancel, slide the cell back
tableView.setEditing(false, animated: true)
}))
self.present(refreshAlert, animated: true, completion: nil)
}
let editAction = UITableViewRowAction(style: .normal, title: "Edit") { action, index in
print("edit button tapped")
}
editAction.backgroundColor = .orange
return [editAction, delete]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With