Monday, 29 February 2016

iOS Swift animation - shake element on input error

We're used to seeing an input element shake when input has failed validation, like a person shaking their head at you. Here's the code to create the animation:

public func errorShake(element: UIView!){
        let animation = CABasicAnimation(keyPath: "position")
        animation.duration = 0.07
        animation.repeatCount = 4
        animation.autoreverses = true
        animation.fromValue = NSValue(CGPoint: CGPointMake( - 10,
        animation.toValue = NSValue(CGPoint: CGPointMake( + 10,
        element.layer.addAnimation(animation, forKey: "position")

No comments:

Post a comment

Comments are moderated, so you'll have to wait a little bit before they appear!