UISnapBehaviour in x-axis only

1k Views Asked by At

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];
2

There are 2 best solutions below

2
On BEST ANSWER

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.

2
On

From UIDynamicBehavior documentation of it's action block:

@property(nonatomic, copy) void (^action)(void)

The dynamic animator calls the action block on every animation step.

So when creating your behaviour, do something like this:

UIView *view = ...
UIAttachmentBehavior *attachment = [[UIAttachmentBehavior alloc] initWithItem:view attachedToAnchor:point];
    
CGFloat xCoordinate = view.frame.origin.x;
attachment.action = ^{
   if (view.frame.origin.x != xCoordinate) {
        CGRect frame = view.frame;
        frame.origin.x = xCoordinate;
        view.frame = frame;
    }
};

[self.dynamicAnimator addBehavior:attachment];

In my example I use a UIAttachmentBehavior but this method will also work for any other subclass of UIDynamicBehavior, in your case a UISnapBehavior.