【问题标题】:Trying to get UIView to bounce using UIKit Dynamics尝试使用 UIKit Dynamics 让 UIView 反弹
【发布时间】:2015-06-18 00:59:58
【问题描述】:

我试图让一个圆形的 UIView 使用 UIKit Dynamics 来“反弹”。它应该在到达屏幕底部时反弹。圆圈是我在 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];
}

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

【问题讨论】:

  • 我最初问为什么球没有下落和弹跳。不仅仅是为什么它一动不动。我编辑了问题中的代码以及结论性问题以纳入您的建议,但不幸的是我仍然遇到了麻烦。您在您的书中指出了您的示例代码,我这样做了,并看到了您在“doButton”方法中添加行为的相关代码块,但遗憾的是我仍然没有找到解决方案。

标签: ios objective-c uiview uikit-dynamics


【解决方案1】:

我的球没有弹起来的原因有两个:

  1. 它没有下降,因为我的 UIDynamicAnimator 对象没有附加重力行为:

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

    [collisionBehavior setTranslatesReferenceBoundsIntoBoundary:YES];
    

特别感谢 Ray Wenderlich,以下article 为我提供了解决方案,以下段落直接引自文章:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-07
    • 2016-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多