Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TableView Swipe to Delete: How to Programmatically Un-swipe

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?

like image 481
Delete My Account Avatar asked Oct 22 '25 00:10

Delete My Account


2 Answers

You can turn off editing on the tableView

[self.tableView setEditing:NO animated:YES];
like image 69
sam_smith Avatar answered Oct 23 '25 15:10

sam_smith


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]
}
like image 33
Martyn Avatar answered Oct 23 '25 15:10

Martyn