How to create a UIView bounce animation?

user3127576 picture user3127576 · Feb 19, 2014 · Viewed 86.5k times · Source

I have the following CATransition for a UIView called finalScoreView, which makes it enter the screen from the top:

CATransition *animation = [CATransition animation];
animation.duration = 0.2;
animation.type = kCATransitionPush;
animation.subtype = kCATransitionFromBottom;
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];

[gameOver.layer addAnimation:animation forKey:@"changeTextTransition"];
[finalScoreView.layer addAnimation:animation forKey:@"changeTextTransition"];

How do I make it so it bounces once after it comes down, then stays still? It should still enter the screen from the top but then bounce when it comes down.

Any help would be much appreciated, thanks!

Answer

huong picture huong · May 7, 2014

A simpler alternative to UIDynamicAnimator in iOS 7 is Spring Animation (a new and powerful UIView block animation), which can give you nice bouncing effect with damping and velocity: Objective C

[UIView animateWithDuration:duration
  delay:delay
  usingSpringWithDamping:damping
  initialSpringVelocity:velocity
  options:options animations:^{
    //Animations
    }
  completion:^(BOOL finished) {
    //Completion Block
}];

Swift

UIView.animateWithDuration(duration,
     delay: delay,
     usingSpringWithDamping: damping,
     initialSpringVelocity: velocity,
     options: options,
     animations: {
            //Do all animations here
            }, completion: {
            //Code to run after animating
                (value: Bool) in
        })

Swift 4.0

UIView.animate(withDuration:duration,
     delay: delay,
     usingSpringWithDamping: damping,
     initialSpringVelocity: velocity,
     options: options,
     animations: {
            //Do all animations here
            }, completion: {
            //Code to run after animating
                (value: Bool) in
        })

usingSpringWithDamping 0.0 == very bouncy. 1.0 makes it smoothly decelerate without overshooting.

initialSpringVelocity is, roughly, "desired distance, divided by desired seconds". 1.0 corresponds to the total animation distance traversed in one second. Example, total animation distance is 200 points and you want the start of the animation to match a view velocity of 100 pt/s, use a value of 0.5.

More detailed tutorial and sample app can be found in this tutorial. I hope this is useful for someone.