ios - UITableView reloadSection 导致缺少显示的单元格

标签 ios swift uitableview realm

我正在使用 Realm Notification 通过插入、修改和删除来更新我的表。

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

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

最佳答案

使用 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/

相关文章:

Swift 3 在解包 Optional 值时意外发现 nil

ios CoreData 与属性的关系

ios - 苹果是否批准存在内存泄漏的 iOS 应用程序?

ios - 更改状态栏的前景色

ios - 如何在 Storyboard 中使用带有一行按钮的自动布局

ios - 如何使用自动布局在自定义 UITableViewCell 中动态设置 UITextView 高度

ios - 一键多 Action TableView自定义Cell

ios - Swift/如何在具有动态高度的 UITableViewCell 中使用具有动态高度的 UITextView

ios - 当我触摸文本字段时如何防止键盘弹出

ios - 通过 iOS SDK 从 Box 流式传输视频 URL