UISwipeGestureRecognizer在if / else语句中执行,而不应该执行

时间:2013-12-30 01:08:43

标签: ios objective-c ios7 uigesturerecognizer sprite-kit

当用户滑动屏幕的左半部分时,我试图在iOS 7 Sprite Kit中运行一个动作。

为了实现这一点,我创建了一个等待触摸事件的for循环,并且在触摸时,有一个if语句检查触摸位置是否小于视图边界的一半。 if语句本身正在正确执行(如果触摸在屏幕的右半部分启动,则else返回正确的NSLog)。但是,无论触摸发生在何处,都会调用UISwipeGestureRecognizer触发的操作。我在下面列出了一个代码示例。

是否有理由不按预期工作?

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesBegan:touches withEvent:event];
for (UITouch *touch in touches) {
    CGPoint touchLocation = [touch locationInView:self.view];
    NSLog(@"Touch location: %f, %f",touchLocation.x,touchLocation.y);

    if (touchLocation.x<self.view.bounds.size.width/2) {
        UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:(self) action:@selector(screenSwipedRight)];
        swipeRight.numberOfTouchesRequired = 1;
        swipeRight.direction=UISwipeGestureRecognizerDirectionRight;
        [self.view addGestureRecognizer:(swipeRight)];

        UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:(self) action:@selector(screenSwipedLeft)];
        swipeLeft.numberOfTouchesRequired = 1;
        swipeLeft.direction=UISwipeGestureRecognizerDirectionLeft;
        [self.view addGestureRecognizer:(swipeLeft)];

        UISwipeGestureRecognizer *swipeUp = [[UISwipeGestureRecognizer alloc] initWithTarget:(self) action:@selector(screenSwipedUp)];
        swipeUp.numberOfTouchesRequired = 1;
        swipeUp.direction=UISwipeGestureRecognizerDirectionUp;
        [self.view addGestureRecognizer:(swipeUp)];
    }
    else {
        NSLog(@"Touches were on the right!");
    }
}
}


-(void)screenSwipedRight
{
    CGFloat percentToRight = 1-(self.playerOne.position.x / self.view.bounds.size.width);
    NSTimeInterval timeToRight = self.horizontalRunSpeed * percentToRight;
    NSLog(@"Percent to right = %f",percentToRight);
    NSLog(@"Time to right = %f",timeToRight);
    SKAction *moveNodeRight = [SKAction moveToX:self.view.bounds.size.width-self.playerOne.size.width duration:timeToRight];
    [self.playerOne runAction:[SKAction sequence:@[moveNodeRight]]];
}

1 个答案:

答案 0 :(得分:2)

  

是否有理由不按预期工作?

是。无论何时在屏幕的左半部分开始触摸,您都会添加一组新的滑动手势识别器。你永远不会删除它们。您永远不会限制手势识别器开始的条件。

这可以解决您的问题:

  1. 删除touchesBegan:withEvent:
  2. 的实施方式
  3. viewDidLoad
  4. 中添加您的手势识别器
  5. 为所有手势识别器设置delegate = self
  6. 添加此代码:

    - (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
        CGPoint touchLocation = [touch locationInView:self.view];
        NSLog(@"Touch location: %f, %f",touchLocation.x,touchLocation.y);
        BOOL shouldBegin = (touchLocation.x < self.view.bounds.size.width / 2);
        return shouldBegin;
    }