ios - 如何在 Swift 中处理重叠的动画调用

标签 ios swift animation animatewithduration

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

  • 隐藏图片 (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

最佳答案

解决方法如下:

如果动画因为在第一个动画完成之前触发第二个动画调用而变得困惑,请阅读这篇文章的答案:

Consecutive Animation Calls Not Working

本质上,它与完成 block 有关。奇怪的是,完成仍然在第一个动画上运行,即使它被打断了。您可以做的是添加一个 if 语句,以便在代码未完成时跳过剩余的完成 block 。

关于ios - 如何在 Swift 中处理重叠的动画调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32699791/

相关文章:

ios - 钛 ti.storekit 返回空产品

xcode - 通过 2 个 View Controller 之间的 segue 传递数据并更新标签

swift - 延迟单元测试

javascript svg 动画

ios - Swift:使用核心数据更新一行[indexPath.row]

ios - 缩小单元格框架与放大框架不同

sqlite - 在 Swift 中访问 SQLite 数据库

css - 变换原点,使动画不跳跃

javascript - AnimationEnd 隐藏另一个 div

objective-c - 定义方法的属性时+和-有什么区别?