因此,目标是以所有插入行都可见的方式进行插入和定位内容。只要插入的行比表本身短,这是可行的。
滚动动画和插入似乎相互干扰。为了解决这个问题,让我们先做滚动,因为文档提供了一个明确的钩子来说明动画何时结束,即委托方法- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
解决方案是这样的:
// about to insert cells at arCells index paths
// first scroll so that the top is visible
NSIndexPath *firstNewIndexPath = [arCells objectAtIndex:0];
NSInteger previousRow = MAX(firstNewIndexPath.row-1, 0);
NSIndexPath *previousIndexPath = [NSIndexPath indexPathForRow:previousRow inSection:firstNewIndexPath.section];
// if the new rows are at the bottom, adjust the content inset so the scrolling can happen
if (firstNewIndexPath.row > [self.tableView numberOfRowsInSection:0) {
self.tableView.contentInset = UIEdgeInsetsMake(0, 0, self.tableView.frame.size.height - 80, 0); // 80 is just to illustrate, get a better row height from the table
}
[self.tableView scrollToRowAtIndexPath:previousIndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
// there may be a better way to setup that scroll, not sure, but that should work.
现在我们有了一个知道动画完成的钩子。我们可以安全地进行插入...
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
// hopefully you have those arCells in an instance variable already, otherwise
// i think you'll need to create one to save state in between the two animations
[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:arCells withRowAnimation:UITableViewRowAnimationLeft];
[self.tableView endUpdates];
// restore the content inset
self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
}
像这样的其他几篇 SO 文章涉及获取一个钩子来告诉我们行动画已完成。这可能会更好,因为这样我们就可以更好地了解滚动到哪里(正如您的问题所暗示的那样,到新插入的行的底部)。但这些似乎都不能确定让我们知道动画已经完成。