Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

indexPath not updated after using deleteRowsAtIndexPaths

I created a method which updates my UITableView when the user wants to delete a cell.

-(void)removeMoreFriendsRow:(NSNotification *)notification {
NSDictionary *d = [notification userInfo];
NSIndexPath *index = [d objectForKey:@"indexPath"];
    
[self.p_currentFriends removeObjectAtIndex:index.row];
    
[self.o_table deleteRowsAtIndexPaths:[NSArray arrayWithObject:index] withRowAnimation:UITableViewRowAnimationRight];
}

p_currentFriends is a NSMutableArray which contains all the objects printed by the UITableView.

This method works fine when I use it once, but it fails when I use it more than once.

It appears that the indexPath stay the same at each call of deleteRowsAtIndexPaths.

For example,

  • at the first call, the user taps on the second cell, indexPath = [0,1] and the correct cell is deleted,
  • at the second call, the user taps on the third cell and indexPath = [0,3] instead of [0,2]

The only way I found to make it works is to use reloadData but I want to have a animation on the cell deletion.

How can I do this?

like image 208
Bou Avatar asked Nov 12 '12 15:11

Bou


3 Answers

What you're doing is basically correct, but you'll need to reload the tableView somehow. If you don't want to reload the whole tableView, use this, which gives you an animation as well -

NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:sectionNum];
[self.o_table reloadSections:indexSet 
            withRowAnimation:UITableViewRowAnimationFade];
like image 195
SomaMan Avatar answered Nov 16 '22 04:11

SomaMan


Swift 2.2

The best solution I found is to set an NSTimer and call the reload data 0.5 sec after, which gives enough time for the animation to finish. The Selector("loadData") is a method that contains tableview.reloadData()

_ = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: Selector("loadData"), userInfo: nil, repeats: false)

Swift 3.0

_ = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(ViewController.loadData), userInfo: nil, repeats: false)
like image 22
Tal Zion Avatar answered Nov 16 '22 04:11

Tal Zion


The reloadSections: method works but it doesn't give you the normal animation for deleting a row, instead using a fade animation. In iOS 11 a new method is available which solves this:

  [tableView performBatchUpdates:^(
  {
    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
  }
             completion:^(BOOL finished)
  {
    if( finished){ 
      [tableView reloadData];
  }
  }];
like image 22
Simon Wigzell Avatar answered Nov 16 '22 04:11

Simon Wigzell