UITableView, Multi Select and Swipe To Delete

I was having a problem recently with a UITableView, where the swipe-to-delete gesture wasn’t working.

The documentation is pretty clear that your table will get the swipe to delete behaviour if you implement the [cci]tableView:commitEditingStyle:forRowAtIndexPath:[/cci] method in your [cci]UITableViewDataSource[/cci] delegate.

So, in other words, implementing this one method in your data source should be enough to enable swiping to delete a row:

[cc lang=”objc”]
– (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
// Delete the row from the data source.
[self.model deleteItemAtIndex:indexPath.row];

// And from the table itself
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
[/cc]

But this wasn’t working for me.

After a bit of digging, I found the problem. My table supports an edit mode that the user flips into by pressing an Edit button in the toolbar. When in edit mode, the user can tap on multiple cells and then tap a trashcan at the bottom to delete all the selected cells. This works nicely, but interferes with the swipe-to-delete gesture, in that swipe-to-delete isn’t supported when multiple selection is enabled in edit mode.

What I wanted was single selection when not in edit mode, and multiple selection when in edit mode. This was easy enough to achieve:

[cc lang=”objc”]
-(void)setEditing:(BOOL)editing animated:(BOOL)animated
{
self.tableView.allowsMultipleSelectionDuringEditing = editing;
[super setEditing:editing animated:animated];
}
[/cc]

Make sure the table is set for Single Selection During Editing in Interface Builder, and that’s it.