0

我试图只更新我的 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
}

干杯。

4

1 回答 1

0

出现抖动动画是因为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
    }
于 2019-01-25T11:16:18.037 回答