1

我有一个页脚栏,它本质上是一个包含按钮和图像的视图。当按下特定按钮时,功能:

  • 隐藏图像 (footerImg)
  • 按钮 (footerBtn) 添加了文本 (textToDisplay)
  • 然后动画将 footerBtn 淡出并重新显示图像
  • 整个动画大约需要2秒

我的问题

我的问题是,有时用户会在 2 秒过去之前再次点击按钮,并且在完成之前会要求运行相同的动画。如何使我的代码能够处理重叠动画?我希望第二次按下停止第一个动画并简单地运行第二个动画。

我的代码

使用下面的代码,按下第二个按钮会破坏动画,文本和图像都会消失两秒钟,然后又回到原始状态。

    //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
4

1 回答 1

2

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.

于 2015-09-29T10:38:04.247 回答