Andrew Andrew - 4 months ago 8
Objective-C Question

UITableView scrolls to top when reloading cells with changing cell heights

I have a table view which contains a placeholders while it loads in images. When the image is loaded, I call

reloadRowsAtIndexPaths:withRowAnimation:
. At this point, the cell changes height, based on the size of the image. When that happens, I want the table view's content offset to remain in place, and for the cells below to be pushed further down, as you might imagine.

The effect I'm getting instead is that the scroll view scrolls back to the top. I'm not sure why this is, and I can't seem to prevent it. Putting
beginUpdates()
before and
endUpdates()
after the
reloadRows
line has no effect.

I am using
estimatedRowHeight
, as is needed as my table view can potentially have hundreds of rows of different heights. I am also implementing
tableView:heightForRowAtIndexPath:
.

EDIT: I've set up a demo project to test this, and admittedly I can't get the demo project to reproduce this effect. I'll keep working at it.

Answer

Always update the UI on the main thread. So just place

[self.tableView reloadData];

inside a main thread:

dispatch_async(dispatch_get_main_queue(), ^{
     //UI Updating code here.
     [self.tableView reloadData];
});
Comments