lavoy lavoy - 1 year ago 264
Objective-C Question

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)];

Answer Source

The best way I found to get my desired behavior is to not animate the insertion at all. The animations were causing the choppyness.

Instead I am calling:

[tableView reloadData];

// set the content offset to the height of inserted rows 
// (2 rows * 44 points = 88 in this example)
[tableView setContentOffset:CGPointMake(0, 88)]; 

This makes the reload appear at the same time as the content offset change.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download