简体   繁体   中英

CellForRowAtIndexPath gets called unexpectedly

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

  1. I click a link in the table view and an external browser is displayed.
  2. I tap on home button and put the app into background.

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,

脚本

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM