How can one insert rows into a UITableView
at the very top without causing the rest of the cells to be pushed down - so the scroll position does not appear to change at all?
Just like Facebook and Twitter when new posts are delivered, they are inserted at the top but the scroll position remains fixed.
My question is similar to this this question. What makes my question unique from that question is that I'm not using a table with fixed row heights - I'm using UITableViewAutomaticDimension
and an estimatedRowHeight
. Therefore the answers suggested there will not work because I cannot determine the row height.
I have tried this solution that doesn't involve taking row height into consideration, but the contentSize
is still not correct after reloading, because the contentOffset
set isn't the same relative position - the cells are still pushed down past where they were before the insert. This is because the cell hasn't been rendered on screen so iOS doesn't bother to calculate the appropriate height for it until it's about to appear, therefore contentSize
is not accurate.
CGSize beforeContentSize = tableView.contentSize;
[tableView reloadData];
CGSize afterContentSize = tableView.contentSize;
CGPoint afterContentOffset = tableView.contentOffset;
tableView.contentOffset = CGPointMake(afterContentOffset.x, afterContentOffset.y + afterContentSize.height - beforeContentSize.height);
Alain pointed out rectForCellAtIndexPath
which forces iOS to calculate the appropriate height. I can now determine the proper height for the inserted cells, but the scroll view's contentSize
is still not correct, as is evidenced when I iterate over all cells and add up the heights which is a larger than contentSize.height
. So ultimately when I set the contentOffset
manually it's not scrolling to the correct location.
Original code:
//update data source
[tableView beginUpdates];
[tableView insertRowsAtIndexPaths:newIndexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
[tableView endUpdates];
In this scenario, what can be done to achieve the desired behavior?