Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IOS 8 UITableView self-sizing cells jump/shift visually when a new view controller is pushed

Here's how I set my table:

self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
self.tableView.delegate = self;
self.tableView.dataSource = self;
self.tableView.estimatedRowHeight = 150;
[self.view addSubview:self.tableView];

Within my cells, I call - (CGSize)sizeThatFits:(CGSize)size to programmatically return the height (which is set in - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath. I'm not using constraints or autolayout.

Nothing complex and my heights are all perfectly laid out visually.

However the problem is when I push a new view controller, the cells jump/shift visually (either up or down). It seems to be jumping based on calculating the estimated row height values - yet sizeThatFits is also called for each visible cell before shifting so I'm really confused (not sure why either needs to be called at all really, since I'm leaving the view). I've checked the contentOffset for the tableView - it's unchanged so it's not the problem.

like image 497
Vadoff Avatar asked Oct 14 '14 21:10

Vadoff


2 Answers

Okay, I solved it by caching my cell heights in sizeThatFits, and returning that value for estimated cell heights within the delegate. Works beautifully.

like image 150
Vadoff Avatar answered Oct 18 '22 13:10

Vadoff


Quick fix:

override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)
    self.tableView.reloadData()
}

Edit: After spending hours on this and similar issues I've found the best solution is to cache the cell heights and return them in estimatedHeightForRowAtIndexPath delegate method, the problem is caused by estimated heights being really inaccurate.

I cached the heights in tableView(_:willDisplayCell:forRowAtIndexPath:) into a dictionary with the unique ID's for the data as keys this way when data gets added or updated I can just remove that height from the cache and use better estimated heights so only that cell uses an estimated height. So far this solves all my jumping and scrolling issues.

like image 35
Steve Avatar answered Oct 18 '22 11:10

Steve