gpt4 book ai didi

swift - CollectionView Cell 中 Label 的值与旧值重叠一毫秒,​​而 reloadItems()

转载 作者:行者123 更新时间:2023-11-28 13:51:56 25 4
gpt4 key购买 nike

我已经针对此行为提出了问题。我想你明白我的意思,如果不明白请问。所以我有一个带有 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.
}

很简单。当我触摸按钮时,数据源的第一个值发生变化,我只为第一个单元格调用重新加载项目函数。

这就是我的 CustomCell 的代码:

class MyCell: UICollectionViewCell {
@IBOutlet weak var cellvalue: UILabel!

最佳答案

使用 reloadItems(at: [IndexPath]),CollectionView 使用默认动画 FadeInOut 自动更新值。您可以通过简单地调用函数 func performBatchUpdates(_ updates: (() -> Void)?, completion: ((Bool) -> Void)? = nil) 并使用动画来避免此动画 block 并将时间设置为 0.0。

UIView.animate(withDuration: 0) {
self.cellectionview.performBatchUpdates({
self.cellectionview.reloadItems(at: [IndexPath(item: 0, section: 0)])
}, completion: nil)
}

关于swift - CollectionView Cell 中 Label 的值与旧值重叠一毫秒,​​而 reloadItems(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54474627/

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