如何在UIPanGestureRecognizer中使用两个操作?

时间:2012-11-19 03:34:11

标签: objective-c xcode uiimageview subview uipangesturerecognizer

我正在使用两个子视图。每一个都是独一无二的,并拥有自己的“行动”。

子视图1 =用户可以拖动视图,旋转和缩放

子视图2 =当用户在屏幕上移动手指时,会在手指触摸的每个点添加图像。

我使用UIPanGestureRecognizer完成了这两项工作。我的问题是,我如何分开这两个行动?我希望能够添加一个子视图,执行所需的操作,然后当我添加其他子视图时,阻止以前的操作发生。

这是我尝试过的,这是在我的panGesture方法中完成的:

 for (UIView * subview in imageView.subviews)
 {
    if ([subview isKindOfClass:[UIImageView class]])
    {
        if (subview == _aImageView)
        {
            CGPoint translation = [panRecognizer translationInView:self.view];
            CGPoint imageViewPosition = _aImageView.center;
            imageViewPosition.x += translation.x;
            imageViewPosition.y += translation.y;

            _aImageView.center = imageViewPosition;
            [panRecognizer setTranslation:CGPointZero inView:self.view];
        }
        else if (subview == _bImageView)
        {
            currentTouch = [panRecognizer locationInView:self.view];

            CGFloat distance = [self distanceFromPoint:currentTouch ToPoint:prev_touchPoint];
            accumulatedDistance += distance;
            CGFloat fixedDistance = 60;

            if ([self distanceFromPoint:currentTouch ToPoint:prev_touchPoint] > fixedDistance)
            {
                [self addbImage];

                prev_touchPoint = currentTouch;
            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

如果您想在两个不同的视图中进行不同的手势识别,请在每个视图上放置单独的识别器。

答案 1 :(得分:0)

通常,您希望视图控制器拥有并管理手势识别器,例如

- (void)viewDidLoad {
    self.panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)];
    self.panGesture.delegate = self;
    [self.viewX addGestureRecognizer:self.panGesture];
    // repeat with other recognisers...
}

请注意,将控制器设置为gestureRecognizer的委托非常重要:这使您可以从视图控制器处理以下委托方法(这是主要问题):

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    // handle your logic, which gestureRecognizer should proceed...
    return NO;
}

处理程序方法与此示例相同,但您可以根据需要设置自己的处理程序:

- (void)handleGesture:(UIGestureRecognizer*)gestureRecognizer {
     // handle gesture (usually sorted by state), e.g.
     // if(gesture.state == UIGestureRecognizerStateEnded) { ... }
}