3.8. Enabling Swipe Deletion of Table View Cells

Problem

You want your application users to be able to delete rows from a table view easily.

Solution

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{
  
  UITableViewCellEditingStyle result = UITableViewCellEditingStyleNone;
  
  if ([tableView isEqual:self.myTableView]){
    result = UITableViewCellEditingStyleDelete;
  }
  
  return result;
  
}

- (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){
    
    if (indexPath.row < [self.arrayOfRows count]){
      
      /* First remove this object from the source */
      [self.arrayOfRows removeObjectAtIndex:indexPath.row];
      
      /* Then remove the associated cell from the Table View */
      [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject: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 ...

Get iOS 5 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.