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()
}