Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIDynamicAnimator - won't work with UIView but will with Self.View?

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!

like image 360
WunDaii Avatar asked Feb 20 '14 00:02

WunDaii


2 Answers

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.

like image 79
danh Avatar answered Nov 04 '22 20:11

danh


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

addSubview(square)
var gravity = UIGravityBehavior(items: [square])
gravity.magnitude = gravitySpeed
animator.addBehavior(gravity)
like image 23
Christos Chadjikyriacou Avatar answered Nov 04 '22 21:11

Christos Chadjikyriacou