IOS UIView Bounce Animation

1.3k views Asked by At

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:

  • Self refers to the container UIView
  • I have also tried changing self for the currentViewController.view, no change.

Edit 2:

  • all of this code is inside the container view implementation file.
3

There are 3 answers

2
BaSha On BEST ANSWER

give a try to make animator property,

@property UIDynamicAnimator *animator;

and then your code,

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

 ...
4
Yan On

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

1
Alen Alexander On

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"];