How to create a bouncing view animation in iOS

The below steps required for doing bounce animation in iOS

1. Add Pan Gesture to the View
2. Translate the view when panning.
3. Reset the view to it's original frame size.
4. Finally add the animation bouncing effect.


1. Add Pan Gesture to the view

- (void)viewDidLoad
{
     UIPanGestureRecognizer* panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanFrom:)];
    [panRecognizer setMaximumNumberOfTouches:1];
    [panRecognizer setDelaysTouchesBegan:TRUE];
    [panRecognizer setDelaysTouchesEnded:TRUE];
    [panRecognizer setCancelsTouchesInView:TRUE];
    [self.view addGestureRecognizer:panRecognizer];
    [panRecognizer release];
}

2. Translate the view when panning 

-(void)handlePanFrom:(UIPanGestureRecognizer *)reconginzer{

    /* TRANSLATE THE UIVIEW */
    CGPoint translation=[reconginzer translationInView:self.view];
    reconginzer.view.center=CGPointMake(reconginzer.view.center.x+translation.x, reconginzer.view.center.y);
/*Don't change the GPoint (0,0) otherwise you will get unexpected results*/
    [reconginzer setTranslation:CGPointMake(0, 0) inView:self.view];

   
    /* AT THE END OF GESTURE
     1. RESET THE VIEW FRAME
     2. CALL BOUNCE ANIMATION METHOD

 */
    if(reconginzer.state==UIGestureRecognizerStateEnded){
       
        [UIView beginAnimations:@"RIGHT-WITH-RIGHT" context:NULL];
        [UIView setAnimationDuration:0.2];
        [UIView setAnimationTransition:UIViewAnimationTransitionNone forView:nil cache:YES];
        [UIView setAnimationBeginsFromCurrentState:YES];
       /* Reset the frame view size*/
        self.view.frame=CGRectMake(0, 0, 1024,768);
        [UIView setAnimationDelegate:self];
      /*  Call bounce animation method */
        [UIView setAnimationDidStopSelector:@selector(bounceBack)];
      [UIView commitAnimations];
    }
 }
4. Finally add the animation bouncing effect.

- (void)bounceBack {
   
    CABasicAnimation *bounceAnimation = [CABasicAnimation animationWithKeyPath:@"position.x"];
    bounceAnimation.duration = 0.2;
    bounceAnimation.repeatCount = 0;
    bounceAnimation.autoreverses = YES;
    bounceAnimation.fillMode = kCAFillModeBackwards;
    bounceAnimation.removedOnCompletion = YES;
    bounceAnimation.additive = NO;
    [self.view.layer addAnimation:bounceAnimation forKey:@"bounceAnimation"];
}

Comments