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];
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.