Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableView insert rows without scrolling

I have a list of data that I'm pulling from a web service. I refresh the data and I want to insert the data in the table view above the current data, but I want to keep my current scroll position in the tableview.

Right now I accomplish this by inserting a section above my current section, but it actually inserts, scrolls up, and then I have to manually scroll down. I tried disabling scrolling on the table before this, but that didn't work either.

This looks choppy and seems hacky. What is a better way to do this?

[tableView beginUpdates];

[tableView insertSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];

[tableView endUpdates];

NSUInteger iContentOffset = 200; //height of inserted rows

[tableView setContentOffset:CGPointMake(0, iContentOffset)];
like image 222
lavoy Avatar asked May 03 '11 16:05

lavoy


1 Answers

If I understand your mission correctly,

I did it in this way:

if(self.tableView.contentOffset.y > ONE_OR_X_ROWS_HEIGHT_YOUDECIDE
{

    self.delayOffset = self.tableView.contentOffset;
    self.delayOffset = CGPointMake(self.delayOffset.x, self.delayOffset.y+ insertedRowCount * ONE_ROW_HEIGHT);

    [self.tableView reloadData];

    [self.tableView setContentOffset:self.delayOffset animated:NO];    


}else
{
    [self.tableView insertRowsAtIndexPath:indexPathArray   WithRowAnimation:UITableViewRowAnimationTop];

}

With this code, If user is in the middle of the table and not the top, the uitableview will reload the new rows without animation and no scrolling. If user is on the top of the table, he will see row insert animation.

Just pay attention in the code, I'm assuming the row's height are equal, if not , just calculate the height of all the new rows you are going to insert. Hope that helps.

like image 159
user1105951 Avatar answered Oct 17 '22 23:10

user1105951