gpt4 book ai didi

ios - UISwipeGestureRecognizer 在不应该执行的情况下在 if/else 语句中执行

转载 作者:行者123 更新时间:2023-11-29 10:50:03 25 4
gpt4 key购买 nike

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

为了实现这一点,我创建了一个等待触摸事件的 for 循环,并且在触摸时,有一个 if 语句检查触摸位置是否小于 View 边界的一半。 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]]];
}

最佳答案

Is there is a reason this is not working as expected?

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

这应该可以解决您的问题:

  1. 删除 touchesBegan:withEvent: 的实现。
  2. viewDidLoad 中添加您的手势识别器。
  3. 为所有手势识别器设置 delegate = self
  4. 添加这段代码:

    - (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;
    }

关于ios - UISwipeGestureRecognizer 在不应该执行的情况下在 if/else 语句中执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20831975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com