UITableView input section on top when scrolling

I am inserting a new section (the section contains 3 cells) at the top of the UITableView while SCROLLING TOP.

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

The section rises correctly. But I need the top of the table ie Cell 0 or row 0. I want this transaction to be smooth. I can insert

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

after endUpdates, but it shows a quick jerk because it takes up the top of the table and then unexpectedly scrolls it to the last position.

How can I make it smooth.

thanks

+7
ios uitableview
source share
1 answer

I have not done extensive testing, but this seems promising:

  • Define NSIndexPath one of the visible cells.
  • Get rectForRowAtIndexPath .
  • Get the current contentOffset table.
  • Add a section, but call reloadData instead of insertSections (which prevents jarring scrolling).
  • Get the updated rectForRowAtIndexPath that you received in step 2.
  • Update contentOffset by the difference of the result from step 5 and step 2.

Thus:

 [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 
+9
source share

All Articles