简体   繁体   English

CellForRowAtIndexPath被意外调用

[英]CellForRowAtIndexPath gets called unexpectedly

I have a tableview with over 12 different types of cells. 我有一个超过12种不同类型的单元格的tableview。 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 一切都可以在iPhone模拟器上完美运行,但是当涉及到iPad模拟器时,一切都很好,直到

  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. 一旦我返回/重新打开该应用程序,表格视图就会自动滚动到一个随机位置,而且,一旦应用程序进入后台,cellForRowAtIndexPath就会被多次调用(仅针对周围/包括显示单元格的索引) ),看起来表格视图会在应用程序进入后台后立即自动滚动。

I'm 100% sure tableview.reloadData() is not called anywhere and applicationDidEnterBackground is not implemented either. 我100%肯定在任何地方都没有调用tableview.reloadData(),也没有实现applicationDidEnterBackground。

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. 我使用XCode 9.3和iPad模拟器以及iOS 9.3和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. 我弄清楚了为什么,这是由于估计的高度不正确,并且tableview做一些奇怪的事情。 IOS 8 UITableView self-sizing cells jump/shift visually when a new view controller is pushed 按下新的视图控制器时,IOS 8 UITableView自调整大小单元格在视觉上跳跃/移动

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. 我通过缓存单元格的高度来解决它,如果未缓存高度,则在UITableViewAutomaticDimension中返回UITableViewAutomaticDimension ,如果缓存了高度,则返回UITableViewAutomaticDimension

Pseudo code - Swift 4: 伪代码-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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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