How to enable swipe to delete cell in a TableView? How to enable swipe to delete cell in a TableView? ios ios

How to enable swipe to delete cell in a TableView?


As Dan has commented above, you need to implement the following table view delegate methods:

  1. tableView:canEditRowAtIndexPath:
  2. tableView:commitEditingStyle:forRowAtIndexPath:

Note: I have tried this in iOS 6 and iOS 7.

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{    // Return YES - we will be able to delete all rows    return YES;}- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{    // Perform the real delete action here. Note: you may need to check editing style    //   if you do not perform delete only.    NSLog(@"Deleted row.");}


You don't have to set editing:YES if you need to show Delete button on cell swipe. You have to implement tableView:canEditRowAtIndexPath: and return YES from there for rows you need to edit/delete. This is not necessary when your tableView's dataSource is a subclass of UITableViewContoller - this method, if not overridden, returns YES by default. In all other cases you have to implement it.

EDIT: Together we have found the problem - tableView:editingStyleForRowAtIndexPath: returned UITableViewCellEditingStyleNone if table wasn't in editing mode.


// Override to support conditional editing of the table view.- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{    // Return NO if you do not want the specified item to be editable.    return YES;}// Override to support editing the table view.- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{    if (editingStyle == UITableViewCellEditingStyleDelete) {        // Delete the row from the data source        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];    }       else if (editingStyle == UITableViewCellEditingStyleInsert) {        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view    }   }