2个同时具有不同方向的各种UIPanGestureRecognizer?

时间:2015-05-14 13:51:00

标签: ios uigesturerecognizer gesture uipangesturerecognizer simultaneous

可以向上,向下,向左和向右平移。

识别器1仅处理垂直平底锅,识别器2仅处理水平平底锅。它们都与同一个委托对象链接。

识别器2完全独立于第一个(除了可以选择所描述的4个方向中的一个方向外)。

那么如何防止其中一个与另一个同时执行?

1 个答案:

答案 0 :(得分:1)

-(void)initPanGestures{
UIPanGestureRecognizer *panGestureRecognizer1 = [[UIPanGestureRecognizer alloc] initWithTarget:self
                                                                action:@selector(handlePan1Gesture:)];

UIPanGestureRecognizer *panGestureRecognizer2 = [[UIPanGestureRecognizer alloc] initWithTarget:self
                                                                                        action:@selector(handlePan2Gesture:)]
}

-(void)handlePan1Gesture:(UIPanGestureRecognizer *)sender{
CGPoint velocity = [sender velocityInView:sender.view];

switch(sender.state) {

        case UIGestureRecognizerStateBegan:
        if(fabs(velocity.y) > fabs(velocity.x)){
            panGestureRecognizer2.enabled=YES;
            panGestureRecognizer1.enabled=NO;
        }
        break;
        case UIGestureRecognizerStateCancelled:
         panGestureRecognizer1.enabled=YES;
        break;
    case UIGestureRecognizerStateEnded:{
        panGestureRecognizer1.enabled=YES;
    }

        break;
}

if(velocity.x > 0)
{
    NSLog(@"gesture went right");
}
else if(velocity.x < 0)
{
    NSLog(@"gesture went left");
}


}

-(void)handlePan2Gesture:(UIPanGestureRecognizer *)sender{
 CGPoint velocity = [sender velocityInView:sender.view];
switch(sender.state) {

    case UIGestureRecognizerStateBegan:
        if(fabs( velocity.x) > fabs(velocity.y)){
            panGestureRecognizer2.enabled=NO;
            panGestureRecognizer1.enabled=YES;

        }
        break;

    case UIGestureRecognizerStateCancelled:
        panGestureRecognizer2.enabled=YES;
        break;
    case UIGestureRecognizerStateEnded:
         panGestureRecognizer2.enabled=YES;
        break;

}


if(velocity.y > 0)
{
    NSLog(@"gesture went down");
}
else if(velocity.y < 0)
{
    NSLog(@"gesture went up");
}

 }

另外,对于两个差异手势,你必须实现委托方法并识别手势。例如,我已经同时使用了两个手势和平移手势

#pragma mark - UIGestureRecognizerDelegate methods
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {

return YES;
}

 - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
if ([panGestureRecognizer1 isEqual:gestureRecognizer]) {

    return [panGestureRecognizer2 isEqual:otherGestureRecognizer];
}

if ([panGestureRecognizer2 isEqual:gestureRecognizer]) {

    return [panGestureRecognizer1 isEqual:otherGestureRecognizer];
}

return NO;
 }