如何使用Swift 3为按钮制作摇动动画 [英] How do you make a shake animation for a button using Swift 3
问题描述
我有一个每隔3秒调用一次的函数。如何为按钮制作摇晃动画,并且左右摇晃。
I have a function that gets called every 3 seconds. How can I make a shaking animation for the button that shakes side to side.
func shakeButton() {
if opened == false {
//Shake Animation
}
}
推荐答案
如果我理解正确的话,试试摇动画。
只需在你的UIButton子类中使用这个方法
if I understood you correctly, try this on shake animation. Simply use this method in your UIButton subclass
class CustomButton: UIButton {
func shake() {
let animation = CAKeyframeAnimation(keyPath: "transform.translation.x")
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.duration = 0.6
animation.values = [-20.0, 20.0, -20.0, 20.0, -10.0, 10.0, -5.0, 5.0, 0.0 ]
layer.add(animation, forKey: "shake")
}
}
然后在某处创建 CustomButton
在代码或storyboard / xib中调用 myButton.shake()
Then you create CustomButton
somewhere in code or storyboard/xib and call myButton.shake()
您可以根据需要采用此解决方案
You can simply adopt this solution on your needs
UPD:我编辑的例子比完全符合你的需要
UPD: I have edit example than exactly fitted your needs
UPD2:另一个解决方案
只需创建 UIButton
扩展
UPD2: another one solution
Just create UIButton
extension
extension UIButton {
func shake() {
let animation = CAKeyframeAnimation(keyPath: "transform.translation.x")
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.duration = 0.6
animation.values = [-20.0, 20.0, -20.0, 20.0, -10.0, 10.0, -5.0, 5.0, 0.0 ]
layer.add(animation, forKey: "shake")
}
}
使用按钮操作回调:
@IBAction func shake(_ sender: UIButton) {
sender.shake()
}
这篇关于如何使用Swift 3为按钮制作摇动动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!