Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableView inserting section at top while scrolling

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

like image 890
Mann Avatar asked Aug 10 '13 17:08

Mann


1 Answers

I haven't done exhaustive testing on this, but this seems promising:

  1. Identify NSIndexPath of one of the visible cells.
  2. Get its rectForRowAtIndexPath.
  3. Get the current contentOffset of the table, itself.
  4. Add the section, but call reloadData instead of insertSections (which prevents jarring scrolling).
  5. Get the updated rectForRowAtIndexPath that you got in step 2.
  6. 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
like image 185
Rob Avatar answered Nov 03 '22 02:11

Rob