J'ai une fonction qui est appelée toutes les 3 secondes. Comment puis-je faire une animation tremblante pour le button qui bouge d'un côté à l'autre.
func shakeButton() { if opened == false { //Shake Animation } }
Si je vous ai bien compris, essayez ceci sur shake animation. Utilisez simplement cette méthode dans votre sous-class UIButton
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") } }
Ensuite, vous créez CustomButton
quelque part dans le code ou storyboard / xib et appelez myButton.shake()
Vous pouvez simplement adopter cette solution selon vos besoins
UPD: J'ai un exemple d'édition que exactement adapté à vos besoins
UPD2: une autre solution Créez simplement l'extension UIButton
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") } }
et utilisez sur vous le callback d'action de button:
@IBAction func shake(_ sender: UIButton) { sender.shake() }
Il est vraiment difficile de savoir ce que vous cherchez ici, sans un échantillon de GIF ou quelque chose. Mais si c'est ce que je pense, où un button se déplace d'un centre initial, à un nouveau centre légèrement à gauche, à un nouveau centre légèrement à droite, et peut-être une autre fois avant de centrer à nouveau, vous devriez regarder UIView animateKeyframes (withDuration: delay: options: animations: achèvement 🙂 méthode.