Reputation: 321
I have a tableview with over 12 different types of cells. I'm using self-sizing and all cells' constraints are set correctly. Everything works perfectly on iPhone simulator, but when it comes to iPad simulator, everything is fine until
Once I go back to/reopen the app, the table view scrolls automatically to a random position, and also, as soon as the app goes into background, cellForRowAtIndexPath is called several times(for just the indexes around/including the displaying cells' indexes), looks like the table view scrolls a bit automatically as soon as the app goes into background.
I'm 100% sure tableview.reloadData() is not called anywhere and applicationDidEnterBackground is not implemented either.
Wondering if anyone has encountered the same problem and what could be the potential causes? I tested with XCode 9.3, iPad simulators with iOS version 9.3 and 11.3.
The scenario looks like the following,
Upvotes: 0
Views: 232
Reputation: 321
I figured out why, it's due to estimated height is not accurate and the tableview is doing some weird things. IOS 8 UITableView self-sizing cells jump/shift visually when a new view controller is pushed
I resolved it by caching the cell heights and returns UITableViewAutomaticDimension
in estimatedHeightForRow if the height is not cached or the cached height if cached.
Pseudo code - Swift 4:
var cellEstimatedHeightCache = [Int: CGFloat]()
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
guard let height = cellEstimatedHeightCache[indexPath.row] else {
return UITableViewAutomaticDimension
}
return height
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cacheCellHeight(row: indexPath.row, height: cell.frame.size.height)
}
private func cacheCellHeight(row: Int, height: CGFloat) {
cellEstimatedHeightCache[row] = height
}
Upvotes: 1