刷新或重新加载 collectionViewCell 中单个对象的数据

Refreshing or reloading data on just single object inside a collectionViewCell

我正在尝试更新我的 costumViewCell 中的一个对象, 我试过 collectionView.reloadItems(at: [IndexPath]),但这种方法更新了我的整个单元格,导致动画非常抖动。

这是我的 collectionView 单元格的示例代码,

class MyCollectionViewCell: UICollectionViewCell {


    @IBOutlet weak var buttonA: UIButton!
    @IBOutlet weak var buttonB: UIButton!


    var myButtonTitle: String? {
        didSet{
            if let title = myButtonTitle {
                self.buttonA.setTitle(title, for: .normal)
            }
        }
    }

    var buttonActionCallBack: (()->()?)

    override func awakeFromNib() {
        super.awakeFromNib()
        self.animation()

        buttonA.addTarget(self, action: #selector(buttonACallBack), for: .touchUpInside)
    }


    @objc fileprivate func buttonACallBack() {
        self.buttonActionCallBack?()
    }


    fileprivate func animation() {
        UIView.animate(withDuration: 1.0) {
            self.buttonA.transform = CGAffineTransform(translationX: 20, y: 20)
            self.buttonB.transform = CGAffineTransform(translationX: 20, y: 20)
        }
    }
}

这是我的数据源方法。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! MyCollectionViewCell

    let item = mainList[indexPath.row]

    collectionView.reloadItems(at: <#T##[IndexPath]#>)
    cell.buttonActionCallBack = {
        () in
        //Do Stuff and Update Just ButtonA Title
    }
    return cell
}

干杯。

抖动动画是因为 collectionView.reloadItems(at: [IndexPath]) 里面写的这行 cellForItemAt 这确实是错误的方法,因为多次调用 cellForItemAt 会导致重新加载的无限循环 IndexPath的。取而代之的是,您只需重新加载发生操作时需要的那部分。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! MyCollectionViewCell
        let item = mainList[indexPath.row]
        //collectionView.reloadItems(at: <#T##[IndexPath]#>) #removed
        cell.buttonActionCallBack = {
            () in
            //Do Stuff and Update Just ButtonA Title
            collectionView.reloadItems(at: [indexPath]) //Update after the change occurs to see the new UI updates
        }
        return cell
    }