Search code examples
iosswiftuicollectionviewcore-animation

Swift collection view button affecting other cells


I have a custom collection view with a mark favorite button at the top which when pressed should show a Instagram like heart animation at the center. What I have done so far causes the heart animation to appear in some other random cells of course that is due to this code of reusing identifier.

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "shopCell", for: indexPath) as! ShopCell

but how should I resolve this issue? I have read multiple posts about it and implemented the solution but none of them worked for me. For example setting index path to cell and after that using delegation on button click

cell.indexPath = indexPath

and in my shop cell I have

@IBAction func favHeartBtn(_ sender: Any) {
    delegate.favoriteButton(sender: self)
}

In my shopView I have this

func favoriteButton(sender: ShopCollectionViewCell) {  
    sender.centerHeart.isHidden = false
    sender.centerHeart.zoomIn()
}

Still animation starts in other cells. Even if I put a check for indexPath


Solution

  • You need to handle the show/hide of the center heart in your custom UICollectionViewCell, i.e.

    class CustomCollectionCell : UICollectionViewCell
    {
        @IBOutlet weak var centerHeart: UILabel!
    
        override func awakeFromNib()
        {
            super.awakeFromNib()
            self.centerHeart.alpha = 0.0
        }
    
        @IBAction func onTapHeartButton(_ sender: UIButton)
        {
            UIView.animate(withDuration: 0.5, animations: { 
                self.centerHeart.alpha = 1.0
            }) { (completed) in
                if completed
                {
                    UIView.animate(withDuration: 0.5, animations: { 
                        self.centerHeart.alpha = 0.0
                    })
                }
            }
        }
    }
    

    You can add whatever animation you need according to your requirement.

    Sample Project: https://github.com/pgpt10/CollectionViewSample