试图让UIView使用UIKit Dynamics进行反弹

时间:2015-06-18 00:59:59

标签: ios objective-c uiview uikit-dynamics

我正在尝试使用UIKit Dynamics获得一个圆形的UIView来“弹跳”。它应该在到达屏幕底部时反弹。圆圈是我在viewDidLoad方法中创建的标准UIView,如下所示:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.orangeBall = [[UIView alloc] initWithFrame:CGRectMake(100.0, 100.0, 50.0, 50.0)];
    self.orangeBall.backgroundColor = [UIColor orangeColor];
    self.orangeBall.layer.cornerRadius = 25.0;
    self.orangeBall.layer.borderColor = [UIColor blackColor].CGColor;
    self.orangeBall.layer.borderWidth = 0.0;
    [self.view addSubview:self.orangeBall];

    // Initialize the property UIDynamicAnimator
    self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];

    [self demoGravity];

}

我试图在demoGravity方法中完成弹跳效果,如下所示:

-(void)demoGravity{

UIGravityBehavior *gravityBehavior = [[UIGravityBehavior alloc] initWithItems:@[self.orangeBall]];

[self.animator addBehavior:gravityBehavior];

UICollisionBehavior *collisionBehavior = [[UICollisionBehavior alloc] initWithItems:@[self.orangeBall]];

[collisionBehavior addBoundaryWithIdentifier:@"myView"
                                   fromPoint:self.orangeBall.frame.origin
                                     toPoint:CGPointMake(self.orangeBall.frame.origin.x, self.orangeBall.frame.origin.y + self.view.frame.size.height)];

[self.animator addBehavior:collisionBehavior];
}

我希望“球”直接落在屏幕上,一旦到达视图的底部,就停止并“反弹”。但是,当我运行我的应用程序时,我看到的只是屏幕顶部的圆圈从屏幕上掉下来。我做错了什么?

1 个答案:

答案 0 :(得分:0)

我的球没弹跳的原因有两个:

  1. 它并没有掉下来,因为我的UIDynamicAnimator对象没有附加gravityBehaviour:

    UIGravityBehavior *gravityBehavior = [[UIGravityBehavior alloc] initWithItems:@[self.orangeBall]];
    
    [self.animator addBehavior:gravityBehavior];
    
  2. 它没有弹跳,因为我需要设置CollisionBehaviour的布尔属性:" TranslatesReferenceBoundsIntoBoundary"到"是"。

    [collisionBehavior setTranslatesReferenceBoundsIntoBoundary:YES];
    
  3. 特别感谢Ray Wenderlich,以下article为我提供了解决方案,以下段落直接引用了文章:

      

    上述代码不是显式添加边界坐标,而是将translatesReferenceBoundsIntoBoundary属性设置为YES。这会导致边界使用提供给UIDynamicAnimator的参考视图的边界。