IOS UIView弹跳动画

时间:2014-05-28 04:52:36

标签: ios physics-engine uidynamicanimator

我有一个UIVIew(容器)和另一个UIView(框),框视图位于ContainerView内。当按下UIButton时,我希望框视图从屏幕底部下拉,并以10px左侧弹跳;然后一旦弹跳停止,我仍然希望盒子显示10px。以下是另一个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];

代码正在运行,但是框没有掉线。

example of layout

编辑1:

  • Self指容器UIView
  • 我也尝试过为currentViewController.view更改self,没有变化。

编辑2:

  • 所有这些代码都在容器视图实现文件中。

3 个答案:

答案 0 :(得分:3)

尝试制作动画师属性,

@property UIDynamicAnimator *animator;

然后是你的代码,

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

 ...

答案 1 :(得分:1)

我认为您没有指定正确的参考视图。它应该是self.viewself.containerView

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

更新 我认为你应该把代码放在这个场景的ViewController中,并且@BaSha建议创建一个动画师属性,点击一下按钮就会添加行为并引用self.containerView 只需确保boxView位于containerView

答案 2 :(得分:1)

以下代码段可以为您的视图提供 BOUNCE EFFECT

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