【问题标题】:CellForRowAtIndexPath gets called unexpectedlyCellForRowAtIndexPath 被意外调用
【发布时间】:2019-01-11 06:56:17
【问题描述】:

我有一个包含超过 12 种不同类型单元格的表格视图。我正在使用自我调整大小,并且所有单元格的约束都已正确设置。在 iPhone 模拟器上一切正常,但在 iPad 模拟器上,一切都很好,直到

  1. 我单击表格视图中的链接并显示外部浏览器。
  2. 我点击主页按钮并将应用程序置于后台。

一旦我返回/重新打开应用程序,表格视图会自动滚动到随机位置,而且,一旦应用程序进入后台,cellForRowAtIndexPath 就会被调用多次(仅用于周围的索引/包括显示单元格的索引),看起来表格视图在应用程序进入后台时会自动滚动一点。

我 100% 确定 tableview.reloadData() 没有在任何地方调用,并且 applicationDidEnterBackground 也没有实现。

想知道是否有人遇到过同样的问题,可能的原因是什么?我使用 XCode 9.3、iOS 版本 9.3 和 11.3 的 iPad 模拟器进行了测试。

场景如下所示,

【问题讨论】:

    标签: ios iphone swift uitableview ipad


    【解决方案1】:

    我明白了原因,这是由于估计的高度不准确,并且 tableview 正在做一些奇怪的事情。 IOS 8 UITableView self-sizing cells jump/shift visually when a new view controller is pushed

    我通过缓存单元格高度解决了这个问题,如果高度未缓存,则在estimatedHeightForRow 中返回UITableViewAutomaticDimension,如果缓存则返回缓存高度。

    伪代码 - 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
    }
    

    【讨论】:

      猜你喜欢
      • 2016-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-04
      • 2021-10-31
      • 1970-01-01
      相关资源
      最近更新 更多