0

I am running UIGravityBehavior and UICollisionBehavior for a custom view. I want that after 2-3 seconds a UISnapBehavior is triggered. Here is my code:

-(void) applyDynamics
{
    _animator = [[UIDynamicAnimator alloc] initWithReferenceView:_referenceView];
    _gravity = [[UIGravityBehavior alloc] initWithItems:@[self]];
    _collision = [[UICollisionBehavior alloc] initWithItems:@[self]];
    _itemBehavior = [[UIDynamicItemBehavior alloc] initWithItems:@[self]];

    [_gravity setGravityDirection:CGVectorMake(0, 1.2)];

    _itemBehavior.elasticity = 0.8f;

    [_collision addBoundaryWithIdentifier:@"AZNotificationBoundary" fromPoint:CGPointMake(0, self.bounds.size.height) toPoint:CGPointMake(_referenceView.bounds.size.width, self.bounds.size.height)];

    [_animator addBehavior:_gravity];
    [_animator addBehavior:_collision];
    [_animator addBehavior:_itemBehavior];

    [self performSelector:@selector(hideAZNotification) withObject:nil afterDelay:2.0];

}

-(void) hideAZNotification
{
    dispatch_async(dispatch_get_main_queue(), ^{
        snap = [[UISnapBehavior alloc] initWithItem:self snapToPoint:CGPointMake(_referenceView.center.x, -10)];

        [_animator addBehavior:snap];
    });
}

I am using [self performSelector] to invoke the hideAZNotification method. The method is invoked but the snap behavior is never attached.

UPDATE:

Weirdly enough the gravity behavior works fine:

-(void) hideNotification
{
    // remove the original gravity behavior
    [_animator removeBehavior:_gravity];

    _gravity = [[UIGravityBehavior alloc] initWithItems:@[self]];
    [_gravity setGravityDirection:CGVectorMake(0, -1)];

    [_animator addBehavior:_gravity];
}
john doe
  • 9,220
  • 23
  • 91
  • 167
  • Add some logging in `hideAZNotification` to make sure everything is as it should be. Are `_animator` and `_referenceView` okay? Is `self` still a subview of the `_referenceView`? I don't see why they would not be, but it is always worth being certain. – matt Mar 27 '14 at 18:54
  • I updated the code. The gravity behavior works fine. – john doe Mar 27 '14 at 19:03
  • Wait. Is `hideNotification` something different from `hideAZNotification`? What the heck is going on here? Would you please just show _all_ the code? – matt Mar 27 '14 at 19:34
  • Sorry! I just renamed the hideAZNotification to hideNotification. – john doe Mar 28 '14 at 02:18
  • Did you do the logging I asked for? Did you try logging `snap` itself just after it is created? If it is nil, there was a problem creating it, and this might be the issue. – matt Mar 28 '14 at 03:09
  • Does the snap behavior work all by itself? In other words, just rewrite `applyDynamics` so that the snap happens there and is the _only_ thing that happens there. I'm betting that it doesn't work (and that the business with the delay is a red herring). – matt Mar 28 '14 at 03:13

0 Answers0