在tableView中,在从数据库下载数据之前,我显示了一个带有一些静态内容的占位符单元格,并更改了该单元格的属性,隐藏了几个按钮并禁用了用户交互。
我刚刚发现的是,即使我删除了indexPath.section 0处的单元部分,当新数据到达并将其插入到相同的索引处时,出列的单元的旧设置也会被缓存。我之前认为,一旦我调用self.tableView.deleteSections(indexVal, with: .automatic)
,该单元将被删除,一个新的单元将出列。有人能给我解释一下这种行为吗?
我知道这是一个微不足道的问题,但我花了几个小时才在一堆代码中找到了这个bug。
var media = [Media]()
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Storyboard.mediaCell, for: indexPath) as! MediaTableViewCell
cell.delegate = self
if firstMessagesLoaded == false {
//hide some buttons and disable userInteraction
cell.isUserInteractionEnabled = true
return cell
}
if firstMessagesLoaded == true {
//it turns out I have to enable userInteraction again here, otherwise it will remain disabled even though the section at this indexPath was deleted previously
// cell.isUserInteractionEnabled = false
return cell
}
}
func fetchMediaChildAdded() {
let newMedia = Media() //received from database ...
//when new media is fetched, remove the placeholder media from array, delete the section and add new data
if self.firstMessagesLoaded == false {
self.firstMessagesLoaded = true
//remove the mediaPlaceholder and delete it's section
self.tableView.beginUpdates()
self.media.remove(at: 0)
let indexVal = IndexSet(integer: 0)
self.tableView.deleteSections(indexVal, with: .automatic)
self.tableView.endUpdates()
if !self.media.contains(newMedia) {
self.media.insert(newMedia, at: 0)
}
}
发布于 2018-08-27 03:00:40
这不是个bug。这是一个特性。
单元被重用(出于性能原因)。这是名称dequeueReusableCell
所暗示的默认行为。
dequeueReusableCell
时,一个单元格将从池中取出。开发人员负责将所有UI元素设置为已定义状态。附注:
第二个条件firstMessagesLoaded == false
永远不会达到,并且beginUpdates / endUpdates
对单个插入/删除操作没有任何影响。
https://stackoverflow.com/questions/52029303
复制相似问题