0

I have a class called DropitBehavior, which is inherited from UIDynamicBehavior. And there are two properties in my UIViewController.

@property (strong, nonatomic) UIDynamicAnimator *animator;
@property (strong, nonatomic) DropitBehavior *dropitBehavior;

The lazy initializers are defined below. And the animation runs correctly.

- (UIDynamicAnimator *)animator
{
    if (!_animator) {
        _animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.gameView];
        //[_animator addBehavior:self.dropitBehavior];
    }

    return _animator;
}

- (DropitBehavior *)dropitBehavior
{
    if (!_dropitBehavior) {
        _dropitBehavior = [[DropitBehavior alloc] init];
        [self.animator addBehavior:_dropitBehavior];
    }

    return _dropitBehavior;
}

But if I call addBehavior in animator initializer, there will be no animation at all. As far as I understand, the animation should run in both ways. What's wrong with the second way?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
amazingjxq
  • 4,487
  • 7
  • 33
  • 35

1 Answers1

1

You're overwriting the getters for the @property's, so judging from your code, the animator isn't created until you call it in the dropitBehavior method.

You would usually add behaviors to the animator in the viewDidLoad or viewWillAppear methods, so you know your views are ready to be animated. You code would look something like this:

- (UIDynamicAnimator *)animator {
    if (!_animator) {
        _animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.gameView];
    }
    return _animator;
}

- (DropitBehavior *)dropitBehavior {
    if (!_dropitBehavior) {
        _dropitBehavior = [[DropitBehavior alloc] init];
    }
    return _dropitBehavior;
}

-(void)viewWillAppear {
    [super viewWillAppear];
    [self.animator addBehavior:self.dropitBehavior];
}
Bob Vork
  • 2,927
  • 28
  • 32