我想只沿y轴拖动dropTarget视图,只是在特定范围内

时间:2014-01-18 11:02:49

标签: ios objective-c cocoa-touch


if ([touch view]==dropTarget1)
{
  CGPoint current = [touch locationInView:self.view];
  if (homeY > 540 && homeY < dropTarget1.frame.origin.y+dropTarget1.frame.size.height)
  {
     dif = current.y - beginY;
     CGRect newDragObjectFrame = CGRectMake(self.dropTarget1.frame.origin.x, homeY+dif,
     self.dropTarget1.frame.size.width,dropTarget1.frame.size.height);
     self.dropTarget1.frame = newDragObjectFrame;
     homeY = homeY+dif;
  }
}

当我使用此代码时,它会向上移动,但我无法再向上或向下移动

1 个答案:

答案 0 :(得分:0)

您遇到的问题可能是由于if声明中的条件造成的。一旦homeY大于540或小于dropTarget1.frame.origin.y+dropTarget1.frame.size.height,条件将永远不再为真(除非homeY在代码中的其他位置更改)并且触摸将被忽略。 我认为获得所需交互的最佳方式是使用UIPanGestureRecognizer。 这是一个如何做到这一点的例子:

// Add this to where you initialize dropTarget1
UIPanGestureRecognizer * panGesture = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePan:)];
panGesture.delegate = self;
[dropTarget1 addGestureRecognizer:panGesture];


- (void)handlePan:(UIPanGestureRecognizer *)recognizer 
{
    CGPoint translation = [recognizer translationInView:self.dropTarget1];
    if (recognizer.view.center.y + translation.y > 80 && recognizer.view.center.y + translation.y < 350)
    {
        recognizer.view.center = CGPointMake(recognizer.view.center.x,recognizer.view.center.y + translation.y);
        [recognizer setTranslation:CGPointMake(0, 0) inView:self.dropTarget1];
    }
}

只需将80和350更改为您实际需要的值即可。您还需要将UIGestureRecognizerDelegate添加到您的班级。

祝你好运!