Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone UITableView Add content at the top without scrolling

I have a potentially very long scrolling log of messages within a UITableView The user would be able to navigate the table by scrolling.

What I'm trying to do is add new content at the top of the table. If the top of the table is visible, the new row would push the rest of the content down. But if the first row of the table is not visible, the table would silently add another row on top without scrolling.

I'm doing this to prevent the table scrolling to the top from interrupting the user browsing data. If I ask the table to simply scroll to the new insertion point, the user's position within the table would be lost, frustrating the user.

One of the ways I can try to implement this is by inserting data into an NSMutableArray at index 0. Would this work? An extra question: how expensive is inserting data at the beginning of an NSMutableArray. I would expect that such operation is optimized, but would like to make sure. What am I missing with this implementation?

Thank you!

like image 212
Alex Stone Avatar asked Oct 29 '11 05:10

Alex Stone


2 Answers

How to insert without bumping the view:

  • Use the tableView's (UIScrollView) contentOffset values to find where the user is currently scrolled to.
  • Add the new row at the top, with animated:NO
  • Update the tableView's contentOffset to be where the user was at plus whatever the height of your row is.

How to avoid causing issues doing this while the user is dragging:

  • Keep track of when the user is dragging, and if you want to insert rows during a drag / motion, add them to a queue that is executed after the user releases.
like image 74
Tim Avatar answered Nov 15 '22 23:11

Tim


CGSize beforeContentSize = self.tableView.contentSize;
[self.tableView reloadData];
CGSize afterContentSize = self.tableView.contentSize;
            
CGPoint afterContentOffset = self.tableView.contentOffset;
CGPoint newContentOffset = CGPointMake(afterContentOffset.x, afterContentOffset.y + afterContentSize.height - beforeContentSize.height);
self.tableView.contentOffset = newContentOffset;
like image 22
nahlamortada Avatar answered Nov 16 '22 00:11

nahlamortada