Search code examples
iosuikit-dynamicsuisnapbehavior

UISnapBehaviour in x-axis only


Is there anyway to get UISnapBevahiour to only work along a linear x-axis?

I want the exact behaviour of a UISnapBehaviour but don't want it to 'shake' into position on both x & y axis, just the x axis.

This is for a UIView inside my contentView of a table cell.

// UIKitDynamics
self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self];
CGPoint centerPoint = self.contentView.center;
self.snapBehaviour = [[UISnapBehavior alloc] initWithItem:self.frontView snapToPoint:centerPoint];
[self.snapBehaviour setDamping:1.0f];
[self.animator addBehavior:self.snapBehaviour];
UIDynamicItemBehavior *itemBehaviour = [[UIDynamicItemBehavior alloc] initWithItems:@[self.frontView]];
itemBehaviour.elasticity = 0.0f;
itemBehaviour.allowsRotation = NO;
[self.animator addBehavior:itemBehaviour];

Solution

  • I'll post the code I used to do a similar thing, as I mentioned in my comment it used UIView animation that leverage UIKit Dynamics underneath as opposed to using them directly...

    [UIView animateWithDuration:0.5
                          delay:0.0
         usingSpringWithDamping:0.5
          initialSpringVelocity:0.3
                        options:UIViewAnimationOptionCurveEaseIn
                     animations:^{
                       [toView setFrame:_modalFrame];
                     }
                     completion:^(BOOL finished) {
                       [self.context completeTransition:YES];
                     }];
    

    This presents modal view which springs up and oscillates a bit on presentation.