为什么 insertRowsAtIndexPaths 总是导致 TableView 滚动到顶部?

Why does insertRowsAtIndexPaths always cause the TableView to scroll to the top?

我已经为这个问题苦苦思索了几个小时,但每次我尝试这样的事情时:

    self.dataArray.append(newCellObj)

然后我这样做:

    self.tableView.beginUpdates()
    self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Top)
    self.tableView.endUpdates()

UITableView 会自动滚动到页面顶部。

即使我尝试:

    self.tableView.scrollEnabled = false
    self.tableView.beginUpdates()
    self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Top)
    self.tableView.endUpdates()

即使完全禁用滚动,UITableView 仍会滚动到顶部。调用 insertRowsAtIndexPaths 后,究竟是什么导致 ScrollView 滚动到顶部?

我对这个问题唯一的解决办法是使用这个:

    self.tableView.reloadData()

相反。如果我使用 reloadData 而不是它很好,但是我失去了我真的很想保留的漂亮动画。

我也有 self.tableView.scrollsToTop = false 并且我已经尝试了许多其他类似的配置,这些配置可能会以某种方式禁用滚动,但是,在 insertRowsAtIndexPaths

之后有一些东西可以覆盖它

我遇到了与 OP 相同的问题。此外,有时我的一些 table 视图单元格会 "blank" 并完全消失,这导致我

对我来说,解决方案是执行以下操作之一:

  • 实施func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
  • 禁用自动布局
  • 在我的 UITableView
  • 上设置更准确的 estimatedRowHeight
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
     return UITableViewAutomaticDimension;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
     return UITableViewAutomaticDimension;
}

// I'm use auto layout and this variant without animation works 
// ...insert object to datasource
NSUInteger idx = [datasource indexOfObject:myNewObject];
if ( NSNotFound != idx )
{
    NSIndexPath *path = [NSIndexPath indexPathForRow:idx inSection:0];
    [self.table beginUpdates];
    [self.table insertRowsAtIndexPaths:@[path]
                      withRowAnimation:UITableViewRowAnimationNone];
    [self.table endUpdates];
    [self.table scrollToRowAtIndexPath:path 
                      atScrollPosition:UITableViewScrollPositionBottom 
                              animated:NO];
}