我有一个每 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")
}
}
然后您在代码或故事板/xib 中的某处创建 CustomButton
并调用 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")
}
}
ans 使用你的按钮操作回调:
ans use on you button action callback:
@IBAction func shake(_ sender: UIButton) {
sender.shake()
}
这篇关于如何使用 Swift 3 为按钮制作摇动动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!