Image view in Collection view found nil when trying to animate in custom class

72 views Asked by At

I am trying to animate an image view that's inside a collection view cell, I have created a custom class for the collection view cells, here's the code:

class HomeCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var cellImage: UIImageView!
    var animator = UIViewPropertyAnimator()

    // Animating the image
    func animateImage() {
        print("Start animation")
        animator = UIViewPropertyAnimator(duration: 0.5, curve: .linear, animations: {
            self.cellImage.transform = self.cellImage.transform.rotated(by: .pi)
        })
        animator.startAnimation()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder:aDecoder)
    
        animateImage()
    }
}

When I run the application, I get this error:

Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

I'm not sure how to fix this, any kind of advice is appreciated.

1

There are 1 answers

0
CloudBalancing On

Is the cell configured as a nib? If so first make sure it is initialized properly. Second call the animateImage from outside the cell. Using the UICollectionViewDelegate methods of willDisplay /didEndDisplaying For more details see - https://developer.apple.com/documentation/uikit/uicollectionviewdelegate#:~:text=A%20collection%20view%20delegate%20manages,object%20to%20its%20delegate%20property.