Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you make a shake animation for a button using Swift 3 [closed]

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
    }
}
like image 977
Nathan C Avatar asked Dec 01 '22 15:12

Nathan C


1 Answers

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()
}
like image 194
Maksym Rachytskyy Avatar answered Dec 04 '22 05:12

Maksym Rachytskyy