Tuesday, March 6, 2012

Deletion of Rows from UITableView

Ok, In one of my previous posts, I posted a code which lets you expand and shrink the row but it wasn't done using

- (void)insertRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation;
- (void)deleteRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation;

Interesting thing about that code is that it doesn't crash , you run it on any version but down point is that it doesn't involve any deletion/insertion animation. You can find that post HERE.

Now I am writing this post to give an insight into how to delete/insert the cells from UITableView. For Deletion, you can get a sample code HERE

What this code does ? Click on any row, it deletes all the rows below the clicked row. You can do it iteratively.


Step 1. Get an array of all those indexPaths which you are going to delete.

  NSMutableArray *array=[[NSMutableArray alloc]init];

  int rowCountInSection=[dataArray count];
  for (int s=start+1; s < start+1+size; s++) {


   NSIndexPath *indexPath = [NSIndexPath indexPathForRow:s inSection:section];
   [array addObject:indexPath];

   }


Step 2. Update your array by deleting items at those index

int k=(rowCountTotal-[indexPath row]-1);
while (k>0)
{
      [dataArray removeLastObject];
      k--;
}


Step 3.Implement deleteRows block code

[tableView beginUpdates];
[tableView deleteRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationAutomatic];
[tableView endUpdates];


No comments:

Post a Comment