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
}
}
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")
}
}
Then you create CustomButton
somewhere in code or storyboard/xib and call myButton.shake()
You can simply adopt this solution on your needs
UPD: I have edit example than exactly fitted your needs
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 use on you button action callback:
@IBAction func shake(_ sender: UIButton) {
sender.shake()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With