简体   繁体   English

仅在x轴上的UISnapBehaviour

[英]UISnapBehaviour in x-axis only

Is there anyway to get UISnapBevahiour to only work along a linear x-axis? 无论如何,是否要使UISnapBevahiour仅沿线性x轴工作?

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. 我想要UISnapBehaviour的确切行为,但不希望它“晃动”到x和y轴(仅x轴)的位置。

This is for a UIView inside my contentView of a table cell. 这是针对我的表格单元格contentView内部的UIView。

 // 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: UIDynamicBehavior文档中可以看到它的action块:

@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. 在我的示例中,我使用UIAttachmentBehavior,但此方法也适用于UIDynamicBehavior的任何其他子类,在您的情况下为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动画在下面利用了UIKit Dynamics,而不是直接使用它们。

[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. 这给出了模态视图,该模态视图在呈现时会弹出并振荡一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM