-
Notifications
You must be signed in to change notification settings - Fork 1
DD 4.4. Enabling Swipe Deletion of Table View Cells
Implement the tableView:editingStyleForRowAtIndexPath: selector in the delegate and the tableView:commitEditingStyle:forRowAtIndexPath: selector in the data source of your table view:
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{ return UITableViewCellEditingStyleInsert; } - (void) setEditing:(BOOL)editing animated:(BOOL)animated{ [super setEditing:editing animated:animated]; [self.myTableView setEditing:editing animated:animated]; } - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{ if (editingStyle == UITableViewCellEditingStyleDelete){ /* First remove this object from the source */ [self.myArray removeObjectAtIndex:indexPath.row]; /* Then remove the associated cell from the Table View */ [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft]; } }
The tableView:editingStyleForRowAtIndexPath: method can enable deletions. It is called by the table view, and its return value determines what the table view allows the user to do (insertion, deletion, etc.). The tableView:commitEdit ingStyle:forRowAtIndexPath: method carries out the user’s requested deletion. The latter method is defined in the delegate, but its functionality is a bit overloaded: not only do you use the method to delete data, but you also have to delete rows from the table here.
The table view responds to the swipe by showing a button on the right side of the targeted row. As you can see, the table view is not in editing mode, but the button allows the user to delete the row.
This mode is enabled by implementing the tableView:editingStyleForRowAtIndex Path: method (declared in the UITableViewDelegate protocol), whose return value indicates whether the table should allow insertions, deletions, both, or neither. By implementing the tableView:commitEditingStyle:forRowAtIndexPath: method in the data source of a table view, you can then get notified if a user has performed an insertion or deletion.