Get swipe direction in Cocoa Touch
I am trying to catch a gesture but it does not work. Here is my code:
UISwipeGestureRecognizer *recognizer;
recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
[recognizer setDirection:(UISwipeGestureRecognizerDirectionRight | UISwipeGestureRecognizerDirectionLeft)];
[[self view] addGestureRecognizer:recognizer];
[recognizer release];
and
-(void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer {
NSLog(@"get gesture");
if (recognizer.direction == UISwipeGestureRecognizerDirectionRight) {
NSLog(@"get gesture right");
}
if (recognizer.direction == UISwipeGestureRecognizerDirectionLeft) {
NSLog(@"get gesture Left");
}
}
It always gets a gesture but does not recognize the direction. I also tried if(recognizer.direction){NSLog(@"get gesture");}
an开发者_StackOverflowd it also worked, so I do not understand where I made the mistake.
Thanks for any help.
You're not using the UISwipeGestureRecognizer
correctly. Its direction is always going to be what you've set it to (in this case UISwipeGestureRecognizerDirectionRight | UISwipeGestureRecognizerDirectionLeft
, or 3).
If you want to capture swipes left and right that you can differentiate between, you'll have to set up a separate recognizer for each. Apple does this in their SimpleGestureRecognizers sample.
What you have to do is just change the codes for adding gesture recognizer.
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];
UISwipe... is iOS. But for Cocoa, you can use -swipeWithEvent:
in your view class. See the documentation at:
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/EventOverview/HandlingTouchEvents/HandlingTouchEvents.html#//apple_ref/doc/uid/10000060i-CH13-SW10
Both gypsicoder and paulbailey's answers are right. For a more detailed solution of mine, see: https://stackoverflow.com/a/16810160/936957
精彩评论