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
}
}
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()
}
It's really hard to know what you're looking for here, without a sample GIF or something. But if it's what I think it is, where a button moves from an initial center, to a new center slightly to a left, to a new center slightly to the right, and maybe another time or two before centering again you should look at UIView's animateKeyframes(withDuration:delay:options:animations:completion:) method.