UITableView inserting section at top while scrolling
ios, uitableview
Solution
I haven't done exhaustive testing on this, but this seems promising:
- Identify `NSIndexPath` of one of the visible cells.
- Get its `rectForRowAtIndexPath`.
- Get the current `contentOffset` of the table, itself.
- Add the section, but call `reloadData` instead of `insertSections` (which prevents jarring scrolling).
- Get the updated `rectForRowAtIndexPath` that you got in step 2.
- Update `contentOffset` by the difference of the result from step 5 and that of 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
Problem
I am inserting new section (section contains 3 cells) top of UITableView while SCROLLING TOP. ``` [_mainTable beginUpdates]; [_mainTable insertSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone]; [_mainTable endUpdates]; ``` Section gets inserting properly. But it takes me top of Table i.e. 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 quick jerk because it takes you top of Table then suddenly scroll it to your last position. How can i make it smooth. Thanks