UIAttachmentBehavior不起作用。 UIDynamicAnimator

时间:2014-11-12 07:13:42

标签: ios objective-c

我无法使用initWithItem:attachedToItem:初始化将动态项的中心点连接到另一个动态项的中心点的附件行为。 但是当我使用方法平移改变顶视图的中心点时,只有顶视图移动,我无法移动另一个视图。它不应该一起移动吗? (顺便说一下,当我把卡片放在顶部时,我正试图实现一堆卡片并一起移动。)

-(void)pinch:(UIPinchGestureRecognizer *)gesture
{
    if(gesture.state ==  UIGestureRecognizerStateChanged){
        CGPoint pinchCen = [gesture locationInView:self.cardArea];
        if (gesture.scale <= 0.5 && !self.pileStat) {
            self.pileStat = !self.pileStat;
            NSUInteger number = [self.cardViews count];
            UIView *topView = [self.cardViews lastObject];
            [topView addGestureRecognizer:[[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(pan:)]];
            for (int i = 0; i < number;i++) {
                UIView *cardView = self.cardViews[i];
                [UIView animateWithDuration:0.5 animations:^{cardView.center = CGPointMake(pinchCen.x+i%10*0.5, pinchCen.y+i%10*0.5);} completion:^(BOOL finished){
                    if(i != number - 1){
                        UIAttachmentBehavior *attach = [[UIAttachmentBehavior alloc]initWithItem:cardView attachedToItem:topView];
                        [self.animator addBehavior:attach];
                    }
                }];
            }

        }
        else if(gesture.scale > 1.5 && self.pileStat)
        {
            self.pileStat = !self.pileStat;
        }
    }else if (gesture.state == UIGestureRecognizerStateEnded){
        gesture.scale = 1.0f;
    }
}
-(void)pan:(UIPanGestureRecognizer *)gesture
{
    if (gesture.state == UIGestureRecognizerStateChanged || UIGestureRecognizerStateEnded) {
    UIView *topView = [self.cardViews lastObject];
        CGPoint trans = [gesture translationInView:self.cardArea];
        topView.center = CGPointMake(trans.x+topView.center.x, trans.y+topView.center.y);
        [gesture setTranslation:CGPointMake(0, 0) inView:self.cardArea];
    }
}

1 个答案:

答案 0 :(得分:1)

setCenter与UIDynamicAnimator不相称。您应该使用附加到触摸上的另一个UIAttachmentBehavior,而不是更改顶视图的中心坐标。用这种方法替换你的pan手势处理程序:

//Add a variable in your interface or header section called "touchAttachment" of type UIAttachmentBehavior
- (void) pan: (UIPanGestureRecognizer *) sender{
  UIView* topCard = [self.cardViews lastObject];
  if (sender.state == UIGestureRecognizerStateBegan){
    _touchAttachment = [[UIAttachmentBehavior alloc] initWithItem:topCard         
      attachedToAnchor: [sender locationInView:self.view]];
    [self.animator addBehavior:_touchAttachment];
  }
  else if (sender.state == UIGestureRecognizerStateChanged){
    [_touchAttachment setAnchorPoint: [sender locationInView: self.view]];
  }
  else if (sender.state == UIGestureRecognizerStateEnded){
    [self.animator removeBehavior: _touchAttachment];
    _touchAttachment = nil;
  }
}

确保添加&#34; touchAttachment&#34;变量。 希望它有所帮助:)