10

I have some trouble to handle swipe on iPhone, I create in my interface a UISwipeGestureRecognizervar:

UISwipeGestureRecognizer *swipeRecognizer;

and in my controller : viewDidLoad method

- (void)viewDidLoad
{
    [super viewDidLoad];


    // Horizontal swipe
    swipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self 
                                                                          action:@selector(swipeMethod:)];
    swipeRecognizer.direction = UISwipeGestureRecognizerDirectionRight | UISwipeGestureRecognizerDirectionLeft; 
    [self addGestureRecognizer:swipeRecognizer];
}

And my method to handle swipe is :

-(void)swipeMethod: (UISwipeGestureRecognizer *) sender
{
    NSLog(@"Swipe!");   
}

When I run my code and do a swipe I got nothing? I'm supposed to get : Swipe!

Thanks.

Girish
  • 4,692
  • 4
  • 35
  • 55
Lekhal
  • 101
  • 1
  • 4
  • Do not add it to self, either use self.view (assuming self is a viewcontroller) or use a subview to put the gesture recognizer on. You can put a breakpoint before putting the recognizer and see if its correctly added. See my answer for left&right swipe detection: http://stackoverflow.com/a/16810160/936957 – Yunus Nedim Mehel May 29 '13 at 09:32

2 Answers2

9

I'm surprised that doesn't crash with an unrecognized selector error. Try adding the recognizer to your view instead of to your view controller:

[self.view addGestureRecognizer:swipeRecognizer]
Anomie
  • 92,546
  • 13
  • 126
  • 145
0

swipeRecognizer.direction = UISwipeGestureRecognizerDirectionRight | UISwipeGestureRecognizerDirectionLeft;

Does this work?

Don't you have to add two gestureRecognizer for each direction?

eugene
  • 39,839
  • 68
  • 255
  • 489
  • Nope. They can be OR'ed. If you 'Jump to Definition' you'll see this. `typedef NS_OPTIONS(NSUInteger, UISwipeGestureRecognizerDirection) { UISwipeGestureRecognizerDirectionRight = 1 << 0, UISwipeGestureRecognizerDirectionLeft = 1 << 1, UISwipeGestureRecognizerDirectionUp = 1 << 2, UISwipeGestureRecognizerDirectionDown = 1 << 3 };` – cnotethegr8 Mar 20 '13 at 09:52