How to make "shaking" animation How to make "shaking" animation xcode xcode

How to make "shaking" animation


Here's the code I use for that effect.

 -(void)shakeView {        CABasicAnimation *shake = [CABasicAnimation animationWithKeyPath:@"position"];        [shake setDuration:0.1];        [shake setRepeatCount:2];        [shake setAutoreverses:YES];        [shake setFromValue:[NSValue valueWithCGPoint:                                 CGPointMake(lockImage.center.x - 5,lockImage.center.y)]];        [shake setToValue:[NSValue valueWithCGPoint:                               CGPointMake(lockImage.center.x + 5, lockImage.center.y)]];        [lockImage.layer addAnimation:shake forKey:@"position"];    }

As Jere mentioned. Make sure to include the import:

#import <QuartzCore/QuartzCore.h>

You can also add it as a category on UIView.


brynbodayles answer also works under iOS8 for a shake animation in swift.

With Import of QuartzCore:

func shakeView(){    var shake:CABasicAnimation = CABasicAnimation(keyPath: "position")    shake.duration = 0.1    shake.repeatCount = 2    shake.autoreverses = true    var from_point:CGPoint = CGPointMake(LoginField.center.x - 5, LoginField.center.y)    var from_value:NSValue = NSValue(CGPoint: from_point)    var to_point:CGPoint = CGPointMake(LoginField.center.x + 5, LoginField.center.y)    var to_value:NSValue = NSValue(CGPoint: to_point)    shake.fromValue = from_value    shake.toValue = to_value    LoginField.layer.addAnimation(shake, forKey: "position")}


func shakeView(_ view: UIView?) {    let shake = CABasicAnimation(keyPath: "position")    shake.duration = 0.1    shake.repeatCount = 2    shake.autoreverses = true    shake.fromValue = NSValue(cgPoint: CGPoint(x: (view?.center.x)! - 5, y: view?.center.y ?? 0.0))    shake.toValue = NSValue(cgPoint: CGPoint(x: (view?.center.x)! + 5, y: view?.center.y ?? 0.0))    view?.layer.add(shake, forKey: "position")}