我为UIButton创建了一个心跳动画.但是,没有办法停止这个动画,因为它是一个无限的代码循环.在修补了许多UIView动画代码块后,我无法UIViewAnimationOptions.Repeat生产出我需要的东西.如果我能做到这一点,我可以简单button.layer.removeAllAnimations()地删除动画.什么是写这个允许删除动画的方法?我可能正在考虑一个计时器,但这可能会让多个动画发生变得混乱.
func heartBeatAnimation(button: UIButton) {
button.userInteractionEnabled = true
button.enabled = true
func animation1() {
UIView.animateWithDuration(0.5, delay: 0.0, options: [], animations: { () -> Void in
button.transform = CGAffineTransformMakeScale(2.0, 2.0)
button.transform = CGAffineTransformIdentity
}, completion: nil)
UIView.animateWithDuration(0.5, delay: 0.5, options: [], animations: { () -> Void in
button.transform = CGAffineTransformMakeScale(2.0, 2.0)
button.transform = CGAffineTransformIdentity
}) { (Bool) -> Void in
delay(2.0, closure: { () -> () in
animation2()
})
}
}
func animation2() {
UIView.animateWithDuration(0.5, delay: 0.0, options: [], animations: { () -> Void in
button.transform = CGAffineTransformMakeScale(2.0, 2.0)
button.transform = CGAffineTransformIdentity
}, completion: nil)
UIView.animateWithDuration(0.5, delay: 0.5, options: [], animations: { () -> Void in
button.transform = CGAffineTransformMakeScale(2.0, 2.0)
button.transform = CGAffineTransformIdentity
}) { (Bool) -> Void in
delay(2.0, closure: { () -> () in
animation1()
})
}
}
animation1()
}
Run Code Online (Sandbox Code Playgroud)
Phi*_*ews 36
这非常有效.阻尼和弹簧需要稍微调整一下,但这解决了这个问题.removeAllAnimations()清除动画并将按钮返回到正常状态.
button.userInteractionEnabled = true
button.enabled = true
let pulse1 = CASpringAnimation(keyPath: "transform.scale")
pulse1.duration = 0.6
pulse1.fromValue = 1.0
pulse1.toValue = 1.12
pulse1.autoreverses = true
pulse1.repeatCount = 1
pulse1.initialVelocity = 0.5
pulse1.damping = 0.8
let animationGroup = CAAnimationGroup()
animationGroup.duration = 2.7
animationGroup.repeatCount = 1000
animationGroup.animations = [pulse1]
button.layer.addAnimation(animationGroup, forKey: "pulse")
Run Code Online (Sandbox Code Playgroud)
这篇文章非常有帮助:CAKeyframeAnimation在重复之前延迟
Swift 5 代码,在脉冲之间没有停顿的情况下工作:
let pulse = CASpringAnimation(keyPath: "transform.scale")
pulse.duration = 0.4
pulse.fromValue = 1.0
pulse.toValue = 1.12
pulse.autoreverses = true
pulse.repeatCount = .infinity
pulse.initialVelocity = 0.5
pulse.damping = 0.8
switchButton.layer.add(pulse, forKey: nil)
Run Code Online (Sandbox Code Playgroud)
小智 5
我创建了这样的东西:
let animation = CAKeyframeAnimation(keyPath: "transform.scale")
animation.values = [1.0, 1.2, 1.0]
animation.keyTimes = [0, 0.5, 1]
animation.duration = 1.0
animation.repeatCount = Float.infinity
layer.add(animation, forKey: "pulse")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7797 次 |
| 最近记录: |