swift - CollectionView 单元中的标签值在 reloadItems() 时与旧值重叠一毫秒
问题描述
我已经针对这种行为提出了一个问题。我想你明白我的意思,如果不是请问。所以我有一个小演示项目,其中包含一个 collectionView 和一个带有整数的数据源。在我的项目中,由于 cpu 使用率较低,我必须通过调用 reloadItems(at: at: [IndexPath]) 来刷新单元格。但是当我用 reloadItems(at: at: [IndexPath]) 刷新一个单元格时,我可以在一毫秒内看到单元格标签中的旧值。它看起来并不完美。
这是我来自 ViewController.swift 的代码
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return datasource.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let mycell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MyCell
mycell.cellvalue.text = String(datasource[indexPath.row])
return mycell
}
@IBOutlet weak var cellectionview: UICollectionView!
@IBAction func touchButton(_ sender: Any) {
if datasource[0] == 1 {
datasource[0] = 3
} else {
datasource[0] = 1
}
cellectionview.reloadItems(at: [IndexPath(item: 0, section: 0)])
}
var datasource: [Int] = [1, 2, 3, 4, 5, 6]
override func viewDidLoad() {
super.viewDidLoad()
cellectionview.dataSource = self
cellectionview.delegate = self
// Do any additional setup after loading the view, typically from a nib.
}
}
很简单。当我触摸按钮时,数据源的第一个值会发生变化,我只需为第一个单元格调用 reload items 函数。
这就是我的 CustomCell 的代码:
class MyCell: UICollectionViewCell {
@IBOutlet weak var cellvalue: UILabel!
}
解决方案
使用reloadItems(at: [IndexPath])
CollectionView 自动更新默认动画 FadeInOut 的值。您可以通过简单地调用函数func performBatchUpdates(_ updates: (() -> Void)?, completion: ((Bool) -> Void)? = nil)
并使用动画块并将时间设置为 0.0 来避免此动画。
UIView.animate(withDuration: 0) {
self.cellectionview.performBatchUpdates({
self.cellectionview.reloadItems(at: [IndexPath(item: 0, section: 0)])
}, completion: nil)
}
推荐阅读
- python - 有没有办法在 Python 3 中快速打印和输出结果
- python - ABRICATE csv 的串联导致蛇形文件
- datetime - dart DateTime 差异错误(28.3 到 27.3 之间)
- java - 在 android studio 中使用 Firebase 记录数据验证用户数据
- java - 用于视图模型中实时数据的观察者的 Lambda 表达式
- python - 根据当前用户 django model admin 过滤对象
- reactjs - URLSearchParams 正在抛出空对象
- c++ - 从 cv::Mat 获取像素值作为数字?
- asp.net-core - 如何在剃刀视图中添加导出按钮以将数据导出到 Excel
- c - c中带有空格的sscanf字符串的替代方法?