user3127576 user3127576 - 1 month ago 13
iOS Question

How to create a UIView bounce animation?

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

With iOS7 and UIKit Dynamics, there is no longer any need to use CAKeyframeAnimations or UIView animations!

Take a look at Apple's UIKit Dynamics Catalog app. Alternately, Teehanlax has a clear, concise tutorial with the full project in github. If you want a more detailed tutorial about the ins-and-outs of dynamics, the Ray Winderlich tutorial is great. As always, the Apple docs are a great first stop, so check out the UIDynamicAnimator Class reference in the docs.

Here's a bit of the code from the Teenhanlax tutorial:

self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];

UIGravityBehavior* gravityBehavior = 
                [[UIGravityBehavior alloc] initWithItems:@[self.redSquare]];
[self.animator addBehavior:gravityBehavior];

UICollisionBehavior* collisionBehavior = 
                [[UICollisionBehavior alloc] initWithItems:@[self.redSquare]]; 
collisionBehavior.translatesReferenceBoundsIntoBoundary = YES;
[self.animator addBehavior:collisionBehavior];

UIDynamicItemBehavior *elasticityBehavior = 
                [[UIDynamicItemBehavior alloc] initWithItems:@[self.redSquare]];
elasticityBehavior.elasticity = 0.7f;
[self.animator addBehavior:elasticityBehavior];

And here are the results

Square bounce

UIKit Dynamics is a really powerful and easy to use addition to iOS7 and you can get some great looking UI from it.

Other examples:

Button bounce Slide bounce Springy collection WWDC sprint collection

The steps to implement UIKit dynamics is always the same:

  1. Create a UIDynamicAnimator and store it in a strong property
  2. Create one or more UIDynamicBehaviors. Each behavior should have one or more items, typically a view to animate.
  3. Make sure that the initial state of the items used in the UIDynamicBehaviors is a valid state within the UIDynamicAnimator simulation.
Comments