使用scrollToRowAtIndexPath滚动到上一个UITableViewCell:atScrollPosition:使用NSFetchedResultsControllerDelegate方法进行动画处理

djb*_*009 7 iphone uitableview nsfetchedresultscontroller ios

我在UITableView的底部添加了一个新项目,在插入项目后,我希望UITableView滚动到最底部以显示新插入的项目.新项目保存到Core Data,UITableView使用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;

   ....
}
Run Code Online (Sandbox Code Playgroud)

这导致出界错误,我似乎无法使其工作.我可以通过调整索引路径的行来滚动到第二个到最后一个注释,但我无法到达最后一个项目.

基本上,我在评论表中添加注释,在添加评论后,我希望表格滚动到最新评论.

Tam*_*ese 16

您需要调用endUpdates以便tableView可以计算其新的部分和行.一个简单的例子看起来像这样:

[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:insertedIndexPath] withRowAnimation:UITableViewRowAnimationFade];
[self.tableView endUpdates];
[self.tableView scrollToRowAtIndexPath:insertedIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
Run Code Online (Sandbox Code Playgroud)

当您使用NSFetchedResultsController,它是更复杂一点,因为呼叫做beginUpdates,insertRowsAtIndexPaths:withRowAnimation:endUpdates通常位于不同的委托方法.那你能做什么呢

  1. 添加属性insertedIndexPath以存储插入的索引路径
  2. -insertRowsAtIndexPaths:withRowAnimation:呼叫-controller:didChangeObject:atIndexPath:,加

    self.insertedIndexPath = insertedIndexPath;
    
    Run Code Online (Sandbox Code Playgroud)
  3. [self.tableView endUpdates]-controllerDidChangeContent:

    if (self.insertedIndexPath) {
        [self.tableView scrollToRowAtIndexPath:self.insertedIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        self.insertedIndexPath = nil;
    }
    
    Run Code Online (Sandbox Code Playgroud)