O'Reilly logo

iOS 5 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required