Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


How do I execute my function in 'stages'?

@IBAction func showCoinFlip() {

        coinImageView.image = #imageLiteral(resourceName: "coinSide")

        let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation")
        rotationAnimation.fromValue = 0.0
        rotationAnimation.toValue = 4 * M_PI
        rotationAnimation.duration = 0.4
        coinImageView.layer.add(rotationAnimation, forKey: nil)

        coinImageView.image = coinProvider.randomCoinSide()



My goal is when the button is pressed the 'coinSide' image is shown and animated to rotate. Then once the animation has ended, I want the coinImageView.image to show the result which .randomCoinSide() will provide. I'm not sure if also there needs to be a delay to disable the button until the final result is shown, so when the whole thing is executed the button can be pressed again to display a new result successfully.

1 Answer

Pasan Premaratne
Pasan Premaratne
Treehouse Teacher

Hey Shayan Rastegar

What you need here is an animation delegate that notifies you when animations start and stop. The class you're looking for is CAAnimationDelegate. If you assign your view controller as a delegate to the rotationAnimation, you can add your logic to show the coin result and enable button in the animationDidStop(_:finished:) method.

The documentation link above has a good example at the top.

If you're not familiar with delegates, you can take the course on it

Thanks Pasan!