Why does insertRowsAtIndexPaths always make TableView scroll up?

I banged my head on this issue for several hours, but every time I try something like this:

self.dataArray.append(newCellObj) 

and then I do this:

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

UITableView will automatically jump to the top of the page.

Even if I try:

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

UITableView will still scroll up, even if scrolling is completely disabled. What exactly makes ScrollView scroll to the top after calling insertRowsAtIndexPaths ?

The only solution I have for this problem is this:

  self.tableView.reloadData() 

instead of this. If I use reloadData instead, but I am losing a nice animation that I really would like to keep.

I also have self.tableView.scrollsToTop = false , and I tried using many other configurations that could disable scrolling in some way, but something that overrides this after insertRowsAtIndexPaths

+5
source share
2 answers

I ran into the same problem as the OP. Also, sometimes some of my table cells look “empty” and disappear altogether, which led me to this related question .

For me, the solution was to make ONE of the following:

  • implement func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
  • disable auto layout
  • set a more accurate estimatedRowHeight to my UITableView
+12
source
 - (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]; } 
0
source

Source: https://habr.com/ru/post/1243538/


All Articles