UITableview: - insertRowsAtIndexPaths:withRowAnimation: - 没有为所有单元格获取动画

时间:2012-10-12 04:35:07

标签: iphone uitableview insert

在我的表格视图中,我插入了一些行

[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:arCells withRowAnimation:UITableViewRowAnimationLeft];
[self.tableView endUpdates];
[self.tableView scrollToRowAtIndexPath:[arCells lastObject] atScrollPosition:UITableViewScrollPositionBottom animated:YES];

我没有获得所有单元格的动画UITableViewRowAnimationLeft。假设如果插入5行,我只获得前2个单元格的动画UITableViewRowAnimationLeft,其余部分插入时没有动画。任何人都可以告诉为什么会这样吗?我做错了吗?

1 个答案:

答案 0 :(得分:0)

因此,目标是以所有插入的行都可见的方式进行插入和定位内容。只要插入的行比表本身短,这是可行的。

似乎滚动动画和插入相互干扰。要修复,让我们首先进行滚动,因为文档为动画完成时提供了一个明确的挂钩,即委托方法- (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 articles like this one处理获取钩子告诉我们行动画已完成。这可能会更好,因为我们有更好的想法滚动到哪里(如你的问题所示,到新插入的行的底部)。但这些似乎都没有让我们知道动画已经完成。