Skip to main content

Shaking animation in Swift

Front-end Development
Back-end Development
Mobile Development

You have probably seen this kind of animation in the wild.  Perhaps after entering an invalid password.  Perhaps when logging into OSX.  This can be easily added to your views in Swift with a simple extension to UIView.

Somewhere in your project (I like to create a file specifically for UIkit extensions) add the following extension.

extension UIView {
  
  func shake() {
    let animation = CABasicAnimation(keyPath: "position")
    animation.duration = 0.07
    animation.repeatCount = 3
    animation.autoreverses = true
    animation.fromValue = NSValue(CGPoint: CGPointMake(self.center.x - 10, self.center.y))
    animation.toValue = NSValue(CGPoint: CGPointMake(self.center.x + 10, self.center.y))
    self.layer.addAnimation(animation, forKey: "position")
  }

}

Then from anywhere in your project when you want to wiggle a view for user feedback you can simply call the shake method like so.

// If login fails
self.loginBoxView.shake()

 

Need a fresh perspective on a tough project?

Let’s talk about how RDG can help.

Contact Us