首页 > 解决方案 > 与 collectionView.reloadItems[at: [indexPath]] 重叠标签值

问题描述

我有一个带有原型单元的 CollectionView。单元格有一个标签。标签经常随时间改变值。我用 重新加载数据collectionView.reloadItems[at: [indexPath]],我的问题是当我使用此方法更新集合视图中的标签时,当标签正在更新他的值时,我眨眼之间就会重叠值:如图所示:

眨眼间的重叠值

当我使用该方法时,collectionView.reloadData()我没有这个问题。但它需要更多的 CPU 功率和时间来更新集合视图。

更多代码:在这里我收集单元格的新数据并将其发送到我的 updateCell 函数:

let btesMeter:[UInt8] = [data![7], data![6], data![5], data![4]]
                let resultMeter = (UInt32(btesMeter[3]) << 24) + (UInt32(btesMeter[2]) << 16) + (UInt32(btesMeter[1]) << 8) + UInt32(btesMeter[0])
                let tempresultMeter = resultMeter / 1000
                updateCell(cellname: "Kilometerstand", newValue: String(tempresultMeter))

这是我的 UpdateCel 函数:

  func updateCell(cellname: String, newValue: String) {
    let cell = cellname
    if let cellname = periodicData.first(where: {$0.title == cell}) {
        if cellname.value == newValue {
            return
        } else {
            cellname.value = newValue
            if let indexOf = periodicData.firstIndex(where: {$0.title == cell}) {
                // Reload the index
                let indexPath = IndexPath(item: indexOf, section: 0)
                let array:[IndexPath] = [indexPath]
                collectionView.reloadItems(at: array)
            }
        }
    }
}

cellForItemAt:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCollectionViewCell
    cell.labelTitle.text = periodicData[indexPath.row].title

    cell.labelValue.text = periodicData[indexPath.row].value
    return cell
}

CustomCollectionViewCell:

class CustomCollectionViewCell: UICollectionViewCell {


@IBOutlet weak var labelTitle: UILabel!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var labelValue: UILabel!

}

标签: swiftlabelcollectionviewreloaddata

解决方案


我没有关于您的代码的足够信息,但这个问题是

prepareForReuse()

可以修复。

执行任何必要的清理以准备再次使用视图。

在您的自定义单元格类中覆盖此函数,并清理任何UILabel,您将在每次重新加载或出列单元格时触发此函数。

你要做什么的一个例子。

override func prepareForReuse() {
    super.prepareForReuse()
    label.text = "" // cleans up the text inside the label to reuse again 
} 

更新:如果上述方法不起作用,

您可能需要在调用reloadData.

您产生这种效果的原因是您用于确定集合视图中的项目和部分数量的源中仍然有旧数据。

验证这一点的一种简单方法是在调用之前对数据源的内容进行 NSLog 记录reloadData

OP

希望这可以帮助!


推荐阅读