Alex Pelletier
Alex Pelletier

Reputation: 5123

IOS UIView Bounce Animation

I have a UIVIew (container) and another UIView (box) the box view is inside of the ContainerView. When a UIButton is pressed I would like the box view to drop down off the bottom of the screen, and bounce with 10px left; then once the bouncing has stopped I still want the box to have 10px showing. Here is some sample code of from another question:

UIDynamicAnimator *animator = [[UIDynamicAnimator alloc] initWithReferenceView:self]; //self is the container

UIGravityBehavior* gravityBehavior = [[UIGravityBehavior alloc] initWithItems:@[box]];
[animator addBehavior:gravityBehavior];

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

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

The code is running when it should but the box isn't dropping.

example of layout

Edit 1:

Edit 2:

Upvotes: 1

Views: 1323

Answers (3)

Alen Alexander
Alen Alexander

Reputation: 735

The following code snippet can provide BOUNCE EFFECT on your views.

CABasicAnimation * animation = [CABasicAnimation animationWithKeyPath:@"position.y"];</br>
[animation setFromValue:[NSNumber numberWithFloat:y-position1]];   
[animation setToValue:[NSNumber numberWithFloat:y-position2]];
[animation setDuration:.7];    //   time gap between the bounces
animation.repeatCount=500;    //    no:of times bounce effect has to be done 
[YOURVIEW.layer addAnimation:animation forKey:@"somekey"];

Upvotes: 1

Yan
Yan

Reputation: 3616

I think you didn't specify the correct reference view. It should be either self.view or self.containerView

UIDynamicAnimator *animator = [[UIDynamicAnimator alloc] initWithReferenceView:self];

Update I think you should put the code in the ViewController for this scene and as @BaSha suggested create a animator property and after a button click you will add the behavior and will reference self.containerView Just make sure that boxView is inside of the containerView

Upvotes: 1

BaSha
BaSha

Reputation: 2406

give a try to make animator property,

@property UIDynamicAnimator *animator;

and then your code,

_animator = [[UIDynamicAnimator alloc] initWithReferenceView:self];

 ...

Upvotes: 3

Related Questions