UIAttachmentBehavior的长度是如何确定的?

时间:2014-05-10 18:22:23

标签: ios cocoa-touch ios7 uikit-dynamics

UIAttachmentView中length属性的documentation如下:

  

创建附件后,如果需要,可使用此属性调整附件长度。系统会根据您初始化附件的方式自动设置初始长度。

我的问题是关于最后一句:如何计算初始长度?

1 个答案:

答案 0 :(得分:2)

初始长度取决于首次创建附件行为时锚点的选择。例如,当您拨打offsetFromCenter时,它是attachedToAnchorinitWithItem:offsetFromCenter:attachedToAnchor:之间的距离。

例如,考虑一下这样的手势识别器:

- (void)handlePan:(UIPanGestureRecognizer *)gesture
{
    static UIAttachmentBehavior *attachment;
    CGPoint location = [gesture locationInView:self.animator.referenceView];

    if (gesture.state == UIGestureRecognizerStateBegan) {
        attachment = [[UIAttachmentBehavior alloc] initWithItem:self.viewToAnimate attachedToAnchor:location];
        NSLog(@"before adding behavior to animator: length = %.0f", attachment.length);       // this says zero, even though it's not really
        [self.animator addBehavior:attachment];
        NSLog(@"after adding behavior to animator:  length = %.0f", attachment.length);       // this correctly reflects the length
    } else if (gesture.state == UIGestureRecognizerStateChanged) {
        attachment.anchorPoint = location;
        NSLog(@"during gesture: length = %.0f", attachment.length);       // this correctly reflects the length
    } else if (gesture.state == UIGestureRecognizerStateEnded || gesture.state == UIGestureRecognizerStateCancelled) {
        [self.animator removeBehavior:attachment];
        attachment = nil;
    }
}

报告:

2014-05-10 14:50:03.590 MyApp[16937:60b] before adding behavior to animator: length = 0
2014-05-10 14:50:03.594 MyApp[16937:60b] after adding behavior to animator:  length = 43
2014-05-10 14:50:03.606 MyApp[16937:60b] during gesture: length = 43
2014-05-10 14:50:03.607 MyApp[16937:60b] during gesture: length = 43

如果您在实例化length之后立即查看UIAttachmentBehavior(但在向动画师添加行为之前),length似乎为零。但只要您将动作添加到动画师,length就会正确更新。