iosswiftanimationanimatewithduration

How to Handle Overlapping Animation Calls in Swift


I have a footer bar which is essentially a view containing a button and an image. When a particular button is pressed the function:

My problem

My problem is that sometimes the user is going to hit the button again before 2 seconds goes by and the same animation will be asked to run before it is finished. How do I enable my code to handle overlapping animations? I want the second press to stop the first animation and simply run the second animation.

My Code

With the code below a second button press ruins the animation and the text AND image both disappear for two seconds and then it goes back to the original state.

    //Animate TaskAction feedback in footer bar
    func animateFeedback(textToDisplay: String, footerBtn: UIButton, footerImg: UIImageView) {

    //Cancel any running animation
    footerBtn.layer.removeAllAnimations()

    //Set to defaults - In case it is interrupting animation
    footerBtn.backgroundColor = UIColor.clearColor()
    footerBtn.setTitleColor(UIColor(red: 55/255.0, green: 55/255.0, blue: 55/255.0, alpha: 1.0), forState: UIControlState.Normal) //light gray

    //Setup for animation
    footerImg.alpha = 0.0
    footerBtn.alpha = 1
    footerBtn.setTitle(textToDisplay, forState: UIControlState.Normal)
    footerBtn.titleLabel!.font = UIFont(name: "HelveticaNeue-Regular", size: 18)

    UIView.animateKeyframesWithDuration(2.0 /*Total*/, delay: 1.0, options: UIViewKeyframeAnimationOptions.CalculationModeLinear, animations: {

        UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration:0.50, animations:{
            footerBtn.alpha = 0.01 //Text fades out
        })

        UIView.addKeyframeWithRelativeStartTime(0.50, relativeDuration:0.50, animations:{
            footerImg.alpha = 1 //Starting image reappears
        })
    },
    completion: { finished in
        footerBtn.setTitle("", forState: UIControlState.Normal)
        footerBtn.alpha = 1
    })//End of animation
}//End of animateFeedback

Solution

  • Here's the solution:

    If an animation gets messed up because a second animation call is triggered before the first animation has finished, read the answer to this post:

    Consecutive Animation Calls Not Working

    Essentially, it has to do with the completion block. Oddly enough, the completion still runs on the 1st animation even if it is interrupted. What you can do is add an if-statement to skip the rest of the completion block if the code didn't finish.