UIDynamicAnimator - 无法与 UIView 一起工作,但可以与 Self.View 一起工作?

6

我使用了苹果公司的示例应用程序中的代码,并根据我的需求进行了调整。 我希望UIImageView gameOverFalling 运行这个方法(下落并弹跳)。 正如您在第2行中所看到的那样,它应该与UIView finalScoreView 相撞。

-(void)gameOverFallingMethod{
    UIDynamicAnimator *animator = [[UIDynamicAnimator alloc] initWithReferenceView:finalScoreView];

    UIGravityBehavior *gravityBeahvior = [[UIGravityBehavior alloc] initWithItems:@[self.gameOverFalling]];
    [animator addBehavior:gravityBeahvior];

    UICollisionBehavior *collisionBehavior = [[UICollisionBehavior alloc] initWithItems:@[self.gameOverFalling]];
    // Apple said: "Creates collision boundaries from the bounds of the dynamic animator's
    // reference view (self.view)."
    collisionBehavior.translatesReferenceBoundsIntoBoundary = YES;
    collisionBehavior.collisionDelegate = self;
    [animator addBehavior:collisionBehavior];

    self.animator = animator;
}

然而,当我运行我的应用程序时,它返回一个Thread 1:SIGABRT错误。在控制台中:

View item (<UIImageView: 0x10aaa0c70; frame = (15 175; 288 42);
  autoresize = RM+BM; userInteractionEnabled = NO; layer = <CALayer: 0x10aa7e0a0>>)
should be a descendant of reference view in <UIDynamicAnimator: 0x10ae17610>
Stopped (0.000000s) in <UIView: 0x10aa9e1e0> {{0, 0}, {288, 195}}

如果我将第二行中的'finalScoreView'替换为'self.view',则它可以起作用,但它会掉到整个屏幕的底部。

你有什么想法吗?我很想知道,谢谢!

3个回答

7
从异常信息可以看出,self.gameOverFalling在您的视图层次结构中并不是由finalScoreView派生而来。请参阅UIDynamicAnimator类参考文档中的引用:

要动画显示视图,请使用initWithReferenceView:方法创建一个animator对象。该引用视图的坐标系将作为animator行为和项的坐标系。 您与此类animator相关联的每个dynamic item都必须是UIView对象,并且必须从引用视图派生。


2
我通过在添加任何行为之前添加子视图来解决了这个问题。
addSubview(square)
var gravity = UIGravityBehavior(items: [square])
gravity.magnitude = gravitySpeed
animator.addBehavior(gravity)

1
您可能忘记使用以下方法将项目添加到引用视图中:
finalScoreView.addSubview(self.gameOverFalling)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接