我为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()
}
答案 0 :(得分:27)
这完美无缺。阻尼和弹簧需要稍微调整一下,但这解决了这个问题。 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")
答案 1 :(得分:8)
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)
答案 2 :(得分:3)
我创造了这样的东西:
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")
答案 3 :(得分:0)
在原始问题上,您提到过您希望动画停止命令。我想你也希望它也能从命令开始。这个解决方案可以做到这两点,而且很简单。
grep
如果需要,可以在任意位置调用cutAnim()来停止动画,在计时器内。
要启动动画,请使用常规按钮操作
grep -l 'str1' * | head
希望这会有所帮助。