首页 > 解决方案 > 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!

}

标签: swiftuicollectionviewoverlayreloadreloaddata

解决方案


使用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)
    }

推荐阅读