Tag Archives: uibutton

Shake animation to a UIView or UIButton

I think button shake is such a nice effect that could be applied to different views especially in cases where you want to indicator an error. On a mobile device where you are limited for screen space a shake effect is even more elegant.

Lets see the button shake in action first:

And here is the small objectiveC code that you can use to produce a similar effect for any UIView, call startShake on the view you want to shake:

- (void) startShake:(UIView*)view
    CGAffineTransform leftShake = CGAffineTransformMakeTranslation(-5, 0);
    CGAffineTransform rightShake = CGAffineTransformMakeTranslation(5, 0);

    view.transform = leftShake;  // starting point

    [UIView beginAnimations:@"shake_button" context:view];
    [UIView setAnimationRepeatAutoreverses:YES]; // important
    [UIView setAnimationRepeatCount:5];
    [UIView setAnimationDuration:0.06];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(shakeEnded:finished:context:)];

    view.transform = rightShake; // end here & auto-reverse

    [UIView commitAnimations];

- (void) shakeEnded:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
    if ([finished boolValue]) {
        UIView* item = (UIView *)context;
        item.transform = CGAffineTransformIdentity;