我正在向 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
时,它有点复杂,因为调用 beginUpdates
、insertRowsAtIndexPaths:withRowAnimation:
和 endUpdates
通常在不同的委托(delegate)方法中。那么你可以做的是
- 添加一个属性
insertedIndexPath
来存储插入的索引路径 在
-controller:didChangeObject:atIndexPath:
中调用-insertRowsAtIndexPaths:withRowAnimation:
后,添加self.insertedIndexPath = insertedIndexPath;
在
-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/