iphone - 使用 scrollToRowAtIndexPath 滚动到最后一个 UITableViewCell :atScrollPosition:animated using NSFetchedResultsControllerDelegate methods

标签 iphone ios uitableview nsfetchedresultscontroller

我正在向 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;

   ....
}

这会导致越界错误,我似乎无法让它工作。我可以通过调整索引路径的行来滚动到倒数第二条评论,但我无法到达最后一项。

基本上,我正在向评论表添加评论,添加评论后,我希望表格滚动到最新的评论。

最佳答案

您需要调用 endUpdates 以便 tableView 可以计算其新的部分和行。一个简单的案例如下所示:

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

当您使用 NSFetchedResultsController 时,它有点复杂,因为调用 beginUpdatesinsertRowsAtIndexPaths:withRowAnimation:endUpdates 通常在不同的委托(delegate)方法中。那么你可以做的是

  1. 添加一个属性insertedIndexPath来存储插入的索引路径
  2. -controller:didChangeObject:atIndexPath: 中调用 -insertRowsAtIndexPaths:withRowAnimation: 后,添加

    self.insertedIndexPath = insertedIndexPath;
    
  3. -controllerDidChangeContent: 中的 [self.tableView endUpdates] 之后,添加

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

关于iphone - 使用 scrollToRowAtIndexPath 滚动到最后一个 UITableViewCell :atScrollPosition:animated using NSFetchedResultsControllerDelegate methods,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11128638/

相关文章:

ios - Base64 或 UIImage。

ios - 在 TableView 中选择行时看到相应的 View Controller

ios - 使用cordova flle transfer将图像/视频保存到IOS中的图库

ios - 如何在 objective-c 中使用 XIB 在登录 View 后创建滑出菜单

iphone - 应用程序配置

ios - 如何为 UITableViewHeaderFooterView 设置 textAlignment?

iphone - UITableView reloadData - cellForRowAtIndexPath 未触发

iphone - DynamoDB - 新放置的项目未反射(reflect)在扫描中

iphone - 奇怪的赋值错误

ios - 如何使用SWRevealViewController在两个 View 之间传递数组?