在Cocoa Touch中获取滑动方向

时间:2011-03-16 07:20:27

标签: objective-c xcode cocoa-touch uigesturerecognizer gesture

我试图抓住一个手势,但它不起作用。这是我的代码:

UISwipeGestureRecognizer *recognizer;
    recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
    [recognizer setDirection:(UISwipeGestureRecognizerDirectionRight | UISwipeGestureRecognizerDirectionLeft)];
    [[self view] addGestureRecognizer:recognizer];
    [recognizer release]; 

-(void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer {
    NSLog(@"get gesture");
    if (recognizer.direction == UISwipeGestureRecognizerDirectionRight) {
        NSLog(@"get gesture right");
    }
    if (recognizer.direction == UISwipeGestureRecognizerDirectionLeft) {
        NSLog(@"get gesture Left");
    }
}

它总是得到一个手势但却无法识别方向。我也试过if(recognizer.direction){NSLog(@"get gesture");}它也有效,所以我不明白我犯了哪个错误。

感谢您的帮助。

4 个答案:

答案 0 :(得分:46)

您没有正确使用UISwipeGestureRecognizer。它的方向始终是您设置的方向(在这种情况下为UISwipeGestureRecognizerDirectionRight | UISwipeGestureRecognizerDirectionLeft或3)。

如果您想要左右捕捉可以区分的滑动,则必须为每个滑动设置单独的识别器。 Apple在SimpleGestureRecognizers sample中执行此操作。

答案 1 :(得分:8)

您只需更改添加手势识别器的代码即可。

UISwipeGestureRecognizer *leftRecognizer;
leftRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
[leftRecognizer setDirection: UISwipeGestureRecognizerDirectionLeft];
[[self view] addGestureRecognizer:leftRecognizer];
[leftRecognizer release];

UISwipeGestureRecognizer *rightRecognizer;
rightRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
[rightRecognizer setDirection: UISwipeGestureRecognizerDirectionRight];
[[self view] addGestureRecognizer:rightRecognizer];
[rightRecognizer release];  

答案 2 :(得分:1)

UISwipe ...是iOS。但是对于Cocoa,您可以在视图类中使用-swipeWithEvent:。请参阅以下文档: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/EventOverview/HandlingTouchEvents/HandlingTouchEvents.html#//apple_ref/doc/uid/10000060i-CH13-SW10

答案 3 :(得分:1)

gypsicoder和paulbailey的答案都是正确的。有关我的更详细解决方案,请参阅:https://stackoverflow.com/a/16810160/936957