我在使用 UITableView
的 didEndDisplayingCell
方法时遇到问题。我将此方法与 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/