gpt4 book ai didi

swift - 重叠标签值与 collectionView.reloadItems[在 : [indexPath]]

转载 作者:行者123 更新时间:2023-11-28 14:06:05 39 4
gpt4 key购买 nike

我有一个带有原型(prototype)单元格的 CollectionView。单元格有一个标签。随着时间的推移,标签经常更改值。我使用 collectionView.reloadItems[at: [indexPath]] 重新加载数据,我的问题是当我使用此方法更新 Collection View 中的标签时,当标签更新他的值时我有一个眨眼重叠值:如图:

Overlapping value while for a blink of an eye

当我使用 collectionView.reloadData() 方法时,我没有遇到这个问题。但是它需要更多的 CPU 能力和时间来更新 Collection View 。

更多代码:在这里,我收集单元格的新数据并将其发送到我的 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!

最佳答案

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

prepareForReuse()

可以修复。

Performs any clean up necessary to prepare the view for use again.

在您的自定义单元格类中覆盖此函数,并清除任何 UILabel,每次重新加载或出队时,您都会触发此功能。

你要做什么的例子。

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

更新:如果以上方法无效,

您可能需要在调用 reloadData 之前清除您的数据源。

产生这种效果的原因是您用于确定 Collection View 中的项目和部分数量的来源仍然包含旧数据。

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

OP

希望这对您有所帮助!

关于swift - 重叠标签值与 collectionView.reloadItems[在 : [indexPath]],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52962043/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com