UIDynamicAnimator - won't work with UIView but

2019-06-23 14:46发布

I used this code from Apple's sample app and adjusted it to mine. I want the UIImageView gameOverFalling to run this method (fall and kind of bounce). It should collide with the UIView finalScoreView, as you can see in line 2.

-(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;
}

However when I run my app, it returns a Thread 1: SIGABRT error. In the console:

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}}

It works when I replace 'finalScoreView' on line 2 with 'self.view', but then it falls to the bottom of the whole screen.

Any ideas what I did wrong? I would love to know, thanks!

3条回答
Summer. ? 凉城
2楼-- · 2019-06-23 15:24

I solved this by adding to subview before adding any behaviour.

addSubview(square)
var gravity = UIGravityBehavior(items: [square])
gravity.magnitude = gravitySpeed
animator.addBehavior(gravity)
查看更多
三岁会撩人
3楼-- · 2019-06-23 15:40

You probably forgot to add your items to the reference view using:

finalScoreView.addSubview(@[self.gameOverFalling])
查看更多
趁早两清
4楼-- · 2019-06-23 15:43

It appears from the exception that self.gameOverFalling does not descend from finalScoreView in your view hierarchy. See the quote from UIDynamicAnimator class reference:

To animate views, create an animator with the initWithReferenceView: method. The coordinate system of the reference view serves as the coordinate system for the animator’s behaviors and items. Each dynamic item you associate with this sort of animator must be a UIView object and must descend from the reference view.

查看更多
登录 后发表回答