如何实现滑动并按住手势识别器?

时间:2013-04-19 20:11:59

标签: ios objective-c uigesturerecognizer gesture uiswipegesturerecognizer

我有两个手势识别器可识别滑动右手势和长按手势。我尝试使用委托方法gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:,但每当我执行滑动和长按手势时,该方法被多次调用而不是一次。我使用以下代码设置手势识别器,调用委托方法,并在执行手势后处理手势。

//Setting up the swipe gesture recognizer
UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeRight:)];
swipeRight.direction = UISwipeGestureRecognizerDirectionRight; 
swipeRight.delegate = self;
[self addGestureRecognizer:swipeRight];

//Setting up the long press gesture recognizer
UILongPressGestureRecognizer *rightLongPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeRight:)];
rightLongPressRecognizer.delegate = self;
rightLongPressRecognizer.tag = PRESS_RIGHT_TAG;
[rightLongPressRecognizer setMinimumPressDuration:0.5];
[self addGestureRecognizer:rightLongPressRecognizer];

//Delegate method
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;   
}

//Method that the gestures call 
-(void)handleSwipeRight: (UIGestureRecognizer *)recognizer {

    self.player.direction = RIGHT;
    [self resetSpriteView];
    [self.playerSprite startAnimating];

    float playerSpriteX = self.playerSprite.center.x;
    float playerSpriteY = self.playerSprite.center.y;
    self.toPoint = CGPointMake(playerSpriteX + TILE_WIDTH, playerSpriteY);
    if(!([self checkIfPlayerHasReachedEnd])) {
        self.fromPoint = CGPointMake(playerSpriteX, playerSpriteY);
        CABasicAnimation *moveAnimation = [CABasicAnimation animation];
        moveAnimation.toValue = [NSValue valueWithCGPoint:CGPointMake(playerSpriteX + TILE_WIDTH, playerSpriteY)];
        [moveAnimation setDelegate:self];
        [moveAnimation setFillMode:kCAFillModeForwards];
        [moveAnimation setRemovedOnCompletion:NO];
        [moveAnimation setDuration:MOVE_ANIMATION_DURATION];
        [self.playerSprite.layer addAnimation:moveAnimation forKey:@"position"];
    }
}

是否有更好的方法来实施滑动并按住手势识别器

1 个答案:

答案 0 :(得分:2)

我认为这里的问题是对代理的作用的误解,以及调用该方法的方式,当执行手势时,实际上是其他内容。

用另一种方法处理长按:

UILongPressGestureRecognizer *rightLongPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];

并处理自己的滑动手势:

UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeRight:)];