ios - UITableView reloadSection 导致缺少显示的单元格
<p><p>我正在使用 Realm 通知来更新我的表,包括插入、修改和删除。 </p>
<pre><code>self.results = realm.objects(PostObject.self).sorted(byKeyPath: "id", ascending: false)
notificationToken = results.addNotificationBlock { (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
}
}
</code></pre>
<p>在第一次更新时,表格会正确显示。第二次调用更新时,tableview 开始丢失单元格。像这样:</p>
<p> <a href="/image/iIzoM.png" rel="noreferrer noopener nofollow"><img src="/image/iIzoM.png" alt="missing cell"/></a> </p>
<p>在这个例子中,删除和修改都是空的,只有插入数组充满了索引。我看到这个问题也是在更新期间滚动表格 View 时引起的。 </p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>在使用 <code>UITableViewCell</code> 的自定义子类时丢失单元格的一个原因是忘记调用 <code>super.prepareForReuse()</code>。</p>
<p>Apple 状态为 <a href="https://developer.apple.com/documentation/uikit/uitableviewcell/1623223-prepareforreuse" rel="noreferrer noopener nofollow">https://developer.apple.com/documentation/uikit/uitableviewcell/1623223-prepareforreuse</a> :</p>
<blockquote>
<p>If you override this method, you must be sure to invoke the superclass
implementation.</p>
</blockquote>
<p>一定要调用 super:</p>
<pre><code>override func prepareForReuse() {
super.prepareForReuse()
// your code follows
}
</code></pre></p>
<p style="font-size: 20px;">关于ios - UITableView reloadSection 导致缺少显示的单元格,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/44248177/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/44248177/
</a>
</p>
页:
[1]