Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a row of a Table in iPhone

I have a UITableView and I want to provide the functionality to user to delete the row when he slips or flicks his finger on the row. I know the editing style which provides a circular red button with -ve sign on it. But How to implement the flicking style. I saw many applications using it, so does apple provide any inbuilt delegate for it or we need to write our own controller for it.

like image 546
rkb Avatar asked Jul 22 '09 22:07

rkb


2 Answers

In order to get the swipe affect you need to implement the table view delegate

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 

method, this will provide access to the swipe interaction for deletion. I typically provide an edit interaction as well for tableviews where deletion is possible since the swipe interaction tends to be a little bit hidden from users.

As an example:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
  [tableView beginUpdates];    
  if (editingStyle == UITableViewCellEditingStyleDelete) {
    // Do whatever data deletion you need to do...
    // Delete the row from the data source
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationTop];   
  }       
  [tableView endUpdates];
}

Hope that helps.

like image 186
paulthenerd Avatar answered Oct 22 '22 03:10

paulthenerd


I'm almost positive that there is a sample application that does this. A more concrete answer will come soon.

UPDATE: iPhoneCoreDataRecipes gives probably exactly what you're looking for.

On topic, here is one of the sweetest provided methods:

// If I want to delete the next 3 cells after the one you click
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  NSMutableArray* indexPaths = [NSMutableArray array];
  for (int i = indexPath.row + 3; i < indexPath.row + 3; i++)
  {
    [indexPaths addObject:[NSIndexPath indexPathForRow:i inSection:0]];
  }

  [tableView beginUpdates];
  [tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
  [tableView endUpdates];
  [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

I think that there is an easier way to accomplish what you want, but then again this is pretty easy. The only difficulty might be deleting yourself...just watch out for segfaults.

like image 23
TahoeWolverine Avatar answered Oct 22 '22 03:10

TahoeWolverine