Shake Animation for UITextField/UIView in Swift

Joe CRONE Scrivens picture Joe CRONE Scrivens · Jan 16, 2015 · Viewed 45.6k times · Source

I am trying to figure out how to make the text Field shake on button press when the user leaves the text field blank.

I currently have the following code working:

if self.subTotalAmountData.text == "" {

    let alertController = UIAlertController(title: "Title", message:
        "What is the Sub-Total!", preferredStyle: UIAlertControllerStyle.Alert)
    alertController.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default,handler: nil))

    self.presentViewController(alertController, animated: true, completion: nil)

} else {

}

But i think it would be much more appealing to just have the text field shake as an alert.

I can't find anything to animate the text field.

Any ideas?

Thanks!

Answer

rakeshbs picture rakeshbs · Jan 16, 2015

You can change the duration and repeatCount and tweak it. This is what I use in my code. Varying the fromValue and toValue will vary the distance moved in the shake.

let animation = CABasicAnimation(keyPath: "position")
animation.duration = 0.07
animation.repeatCount = 4
animation.autoreverses = true
animation.fromValue = NSValue(cgPoint: CGPoint(x: viewToShake.center.x - 10, y: viewToShake.center.y))
animation.toValue = NSValue(cgPoint: CGPoint(x: viewToShake.center.x + 10, y: viewToShake.center.y))

viewToShake.layer.add(animation, forKey: "position")