【问题标题】:UITableView reloadSection cause missing displayed cellsUITableView reloadSection 导致缺少显示的单元格
【发布时间】:2017-05-29 17:58:33
【问题描述】:

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

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 开始丢失单元格。像这样:

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

【问题讨论】:

  • 您是否检查过正在执行回调的线程?如果不在主线程上,可以用dispatch_async将它分派到主队列
  • 是的,我已经将它分派到主队列,如下所示:DispatchQueue.main.async { /* begin - insert - end */ }。如果在更新期间不滚动,我看到表格没有这个问题。
  • 您发布的代码中没有任何内容显示不正确。演示该问题的完整 Xcode 项目可能 1) 帮助您找出您做错了什么或 2) 帮助 Realm 人员(嗨!)识别 Realm 中的错误。
  • 听起来很奇怪,但现在,在我删除了我在“cellForRowAtIndex”中使用的 html 解码函数后,表格可以完美运行。我还看到,现在它仅在用户停止滚动时才执行更新。

标签: ios swift uitableview realm


【解决方案1】:

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

Apple 在https://developer.apple.com/documentation/uikit/uitableviewcell/1623223-prepareforreuse 声明:

如果你重写这个方法,你必须确保调用超类 实施。

一定要调用 super:

override func prepareForReuse() {
    super.prepareForReuse()

    // your code follows
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 2016-07-08
    • 1970-01-01
    相关资源
    最近更新 更多