UIContextualAction with destructive style seems to delete row by default

Viewed 6404

The problem I'm seeing is that when I create a UIContextualAction with .destructive and pass true in completionHandler there seems to be a default action for removing the row.

If you create a new Master-Detail App from Xcode's templates and add this code in MasterViewController...

override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let testAction = UIContextualAction(style: .destructive, title: "Test") { (_, _, completionHandler) in
        print("test")
        completionHandler(true)
    }
    return UISwipeActionsConfiguration(actions: [testAction])
}

the row you swipe will be removed. Notice that there's no code there updating the table view. Also the model is not updated and if you scroll way up to cause the row to be reloaded it will reappear.

Passing false in this case does not remove the row. Or using the .normal style and true also does not remove the row.

.destructive and true results in the row being removed by default.

Can anyone explain this behaviour? Why is the row being removed?

4 Answers

I can't reproduce this issue in iOS 13. Either the behavior in iOS 12 and before was a bug or it has simply been withdrawn (perhaps because it was confusing).

In iOS 13, if you just return from a .destructive action by calling completion(true) without doing anything, nothing happens and that's the end of the matter. The cell is not deleted for you.

I agree with the answer by Kris Gellci, but notice that if you are using a NSFetchedResultsController it may complicate things. It seems that for a destructive UIContextualAction the call completion(true) will delete the row, but so may the NSFetchedResultsController's delegate. So you can easily end up with errors in that way. With NSFetchedResultsController I decided to call completion(false) (to make the contextual menu close), regardless of whether the action was a success or not, and then let the delegate take care of deleting the table row if the corresponding object has been deleted.

Use the below flag for disabling full swipe.

performsFirstActionWithFullSwipe

By default it will automatically performs the first action which is configured in UISwipeActionsConfiguration. so if you want to disable full swipe delete then set "performsFirstActionWithFullSwipe" as false.

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let test = UIContextualAction(style: .destructive, title: "test") { (action, view, completion) in
        
        // Your Logic here
        completion(true)
    }
    
    let config = UISwipeActionsConfiguration(actions: [test])
    config.performsFirstActionWithFullSwipe = false
    return config
} 

Hope this will solve your problem.

Related