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(element.center.x - 10, element.center.y))
        animation.toValue = NSValue(CGPoint: CGPointMake(element.center.x + 10, element.center.y))
        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!