ios - UITableView 调用 didEndDisplayingCell 不正确

标签 ios swift uitableview swift3

我在使用 UITableViewdidEndDisplayingCell 方法时遇到问题。我将此方法与 willDisplayCell 一起使用来为我的表处理一些额外的数据跟踪。问题是 didEndDisplayingCell 被连续多次调用,有时单元格实际上仍在显示。我不明白为什么会这样。

更多详情

我正在使用 NSFetchedResultsController 为表格提供数据。更改从不同队列上的 NSManagedObjectContext 进入表,然后合并到表使用的 NSManagedObjectContext 中。这一切似乎工作正常。查看我对上述方法的实现:

override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    debugPrint("willDisplay cell at \(indexPath).")
    self.dataProvider.addTrackedRelatedRecords(for: indexPath)
}

override func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    debugPrint("didEndDisplaying cell at \(indexPath).")
    self.dataProvider.removeTrackedRelatedRecords(for: indexPath)
}

我在这里看到的输出是:

 "Updating rows in table at [0, 0]". <=== This is an update to the data
 "willDisplay cell at [0, 0]."       <=== This is what I expect
 "didEndDisplaying cell at [0, 0]"
 "didEndDisplaying cell at [0, 0]"
 "didEndDisplaying cell at [0, 0]"

该单元格在表格中保持可见并且永远不会消失。我看不到任何东西会导致调用 didEndDisplaying,尤其是重复调用。

我可以通过将以下内容添加到 didEndDisplayingCell 方法来检查单元格是否实际上仍然可见来解决此问题:

override func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    debugPrint("didEndDisplaying cell at \(indexPath).")
    // WORK AROUND
    if let visibleRows = tableView.indexPathsForVisibleRows, visibleRows.contains(indexPath) {
        return
    }
    self.dataProvider.removeTrackedRelatedRecords(for: indexPath)
}

这正确地看到单元格仍然可见,因此不会删除我的额外跟踪。但是,如果单元格可见,为什么要调用该方法?

显然,我的应用程序中还有很多其他代码在工作。我将尝试将其归结为一个非常简单的案例,但我想我会先发布这个,看看是否有人看到过可能发生这种情况的案例。这可能会帮助我找到它。

感谢您的任何见解。

最佳答案

我发现了这个问题并发布了一个答案,以防其他人看到这个问题并且会从我发现的内容中得到帮助。

事实证明,我无意中在 tableView.beginUpdates()tableView.endUpdates() block 。

我相信 reloadRows 导致单元格被替换,这将导致 didEndDisplayingCell。而且,由于 block 内发生了一些更新,因此一旦 tableView.endUpdates() 被调用,这些更新就会被排队并发布。

删除 reloadRows 调用解决了问题,一切都按预期工作。

关于ios - UITableView 调用 didEndDisplayingCell 不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43525403/

相关文章:

ios - 状态栏颜色 - iphone 横向问题

swift - XCTest UITests 在应用启动时失败,并显示过期 token 错误

swift - 如何判断 facebook 和 gmail firebase 用户是否已创建

ios - 可变数组 iOS 中的最大元素

ios - Metal 地址空间说明符“设备”

ios - Cordova 5.3.1 和 iOS9 平台 - 我无法从外部源加载图像和脚本

json - 使用 swift Codable 从 JSON 数组中提取数据

ios - 使用自定义表格 View 单元格检测用户所在的单元格

ios - 设置默认时区不成功

iphone - 在-tableView :heightForRowAtIndexPath: when there is a section index present期间获取tableview单元格的真实宽度