UITableView插入部分在滚动顶部

我插入新的部分(部分包含3单元格)顶部的UITableView,而滚动顶部。

[_mainTable beginUpdates]; [_mainTable insertSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone]; [_mainTable endUpdates]; 

节正确插入。 但它使我的表格,即单元格0或行0的顶部。我希望这个交易顺利。 我可以插入

 [_mainTable scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:1] atScrollPosition:UITableViewScrollPositionBottom animated:NO]; 

endUpdates后,但它显示快速混蛋,因为它需要你的表顶部,然后突然滚动到您的最后一个位置。

我怎样才能使它光滑。

谢谢

我没有做过这方面的详尽testing,但这似乎很有希望:

  1. 确定其中一个可见单元格的NSIndexPath
  2. 获取它的rectForRowAtIndexPath
  3. 获取表格的当前contentOffset ,本身。
  4. 添加部分,但调用reloadData而不是insertSections (这可以防止滚动)。
  5. 获取步骤2中获得的更新的rectForRowAtIndexPath
  6. 根据步骤5和步骤2的结果的差异更新contentOffset

从而:

 [self.sections insertObject:newSection atIndex:0]; // this is my model backing my table NSIndexPath *oldIndexPath = self.tableView.indexPathsForVisibleRows[0]; // 1 CGRect before = [self.tableView rectForRowAtIndexPath:oldIndexPath]; // 2 CGPoint contentOffset = [self.tableView contentOffset]; // 3 [self.tableView reloadData]; // 4 NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:oldIndexPath.row inSection:oldIndexPath.section + 1]; CGRect after = [self.tableView rectForRowAtIndexPath:newIndexPath]; // 5 contentOffset.y += (after.origin.y - before.origin.y); self.tableView.contentOffset = contentOffset; // 6