swift - 与 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!
}
解决方案
我没有关于您的代码的足够信息,但这个问题是
prepareForReuse()
可以修复。
执行任何必要的清理以准备再次使用视图。
在您的自定义单元格类中覆盖此函数,并清理任何UILabel
,您将在每次重新加载或出列单元格时触发此函数。
你要做什么的一个例子。
override func prepareForReuse() {
super.prepareForReuse()
label.text = "" // cleans up the text inside the label to reuse again
}
更新:如果上述方法不起作用,
您可能需要在调用reloadData
.
您产生这种效果的原因是您用于确定集合视图中的项目和部分数量的源中仍然有旧数据。
验证这一点的一种简单方法是在调用之前对数据源的内容进行 NSLog 记录reloadData
。
希望这可以帮助!
推荐阅读
- qt - 在QDialogButtonBox中,对话框关闭时它在哪里断开按钮的销毁连接?
- r - 在 R 中,如果我分配数据框,它不会在印地语中获取数据
- php - 如何在 GRID 和 LIST 模式下在类别页面上显示自定义属性
- mysql - 如何在 Codeigniter 中忘记密码,密码通过电子邮件发送
- java - 使用 javax.ws.rs 将 XML 转换为带有反斜杠的 json
- ruby - 如何解决命令执行的 UTF-8 问题
- jquery - 轮播项目在 Bootstrap 中没有水平显示
- java - Java中的堆栈溢出错误后如何进行堆转储?
- spring-boot - spring-boot 单元测试获取应用程序属性
- laravel - 此集合实例上不存在属性 [title]。拉拉维尔 5.6