Scroll to the last UITableViewCell using scrollToRowAtIndexPath: atScrollPosition: animated using NSFetchedResultsControllerDelegate methods

I add a new element at the bottom of the UITableView and after inserting the element, I want the UITableView to scroll to the very bottom level to display the newly inserted element. New items are saved in Core Data, and the UITableView is automatically updated using NSFetchedResultsController.

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath { switch (type) { case NSFetchedResultsChangeInsert: NSLog(@"*** controllerDidChangeObject - NSFetchedResultsChangeInsert"); [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade]; //THIS IS THE CODE THAT DOESN'T WORK [self.tableView scrollToRowAtIndexPath:newIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES]; break; .... } 

This leads to an error outside the boundaries, I can not get it to work. I can go to the second to the last comment by adjusting the index path line, but I cannot get to the very last element.

Basically, I add a comment to the comment table and after adding a comment, I want the table to scroll to the last comment.

+7
source share
2 answers

You need to call endUpdates so that the tableView can calculate its new sections and rows. A simple case would look like this:

 [self.tableView beginUpdates]; [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:insertedIndexPath] withRowAnimation:UITableViewRowAnimationFade]; [self.tableView endUpdates]; [self.tableView scrollToRowAtIndexPath:insertedIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES]; 

How you use NSFetchedResultsController is a bit more complicated since calls to beginUpdates , insertRowsAtIndexPaths:withRowAnimation: and endUpdates are usually in different delegate methods. What you could do is

  • add the insertedIndexPath property to store the inserted pointer path
  • after calling -insertRowsAtIndexPaths:withRowAnimation: in -controller:didChangeObject:atIndexPath: add

     self.insertedIndexPath = insertedIndexPath; 
  • after [self.tableView endUpdates] in -controllerDidChangeContent: add

     if (self.insertedIndexPath) { [self.tableView scrollToRowAtIndexPath:self.insertedIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES]; self.insertedIndexPath = nil; } 
+16
source

See if this helps ...

 [self.tableView beginUpdates]; [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade]; [self.tableView endUpdates]; [self.tableView scrollToRowAtIndexPath:newIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES]; 
0
source

All Articles