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

  • ignoring file missing required architecture i386 in file
  • Gesture recognition with UIWebView
  • Properties and Instance Variables in Objective-C
  • NSDate not returning correct date
  • Calling other tools from my tool
  • UIAlertView Button Action
  • -(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");} and it also worked, so I do not understand where I made the mistake.

    Thanks for any help.

    4 Solutions Collect From Internet About “Get swipe direction in Cocoa Touch”

    You’re not using the UISwipeGestureRecognizercorrectly. 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];  
    

    Both gypsicoder and paulbailey’s answers are right. For a more detailed solution of mine, see: https://stackoverflow.com/a/16810160/936957