OGeek|极客世界-中国程序员成长平台

标题: ios - UITableView reloadSection 导致缺少显示的单元格 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:46
标题: ios - UITableView reloadSection 导致缺少显示的单元格

我正在使用 Realm 通知来更新我的表,包括插入、修改和删除。

self.results = realm.objects(PostObject.self).sorted(byKeyPath: "id", ascending: false)

notificationToken = results.addNotificationBlock { [weak self] (changes: RealmCollectionChange) in
        guard let tableView = self?.tableView else { return }
        switch changes {
        case .initial:

            tableView.reloadData()

            break
        case .update(_, let deletions, let insertions, let modifications):

            tableView.isUserInteractionEnabled = false

            tableView.beginUpdates()
            tableView.deleteSections(IndexSet(deletions), with: .automatic)
            tableView.insertSections(IndexSet(insertions), with: .automatic)
            tableView.reloadSections(IndexSet(modifications), with: .automatic)
            tableView.endUpdates()

            tableView.isUserInteractionEnabled = true

            break
        case .error(let error):

            fatalError("\(error)")

            break
        }
}

在第一次更新时,表格会正确显示。第二次调用更新时,tableview 开始丢失单元格。像这样:

missing cell

在这个例子中,删除和修改都是空的,只有插入数组充满了索引。我看到这个问题也是在更新期间滚动表格 View 时引起的。



Best Answer-推荐答案


在使用 UITableViewCell 的自定义子类时丢失单元格的一个原因是忘记调用 super.prepareForReuse()

Apple 状态为 https://developer.apple.com/documentation/uikit/uitableviewcell/1623223-prepareforreuse :

If you override this method, you must be sure to invoke the superclass implementation.

一定要调用 super:

override func prepareForReuse() {
    super.prepareForReuse()

    // your code follows
}

关于ios - UITableView reloadSection 导致缺少显示的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44248177/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4