Using UISwipeGestureRecognizer in UIScrollView, can't detect right swipe, only detect left swipe

Vigor picture Vigor · Sep 4, 2012 · Viewed 7.6k times · Source

I have a UIView demoView in a UIScrollView. I want to scroll the UIScroll view vertically and don't scroll horizontally. I add UISwipeGestureRecognizer to the UIView. The code is (self here is the UIScrollView):

self.demoView.userInteractionEnabled = YES;
UISwipeGestureRecognizer *rightSwipe = [[UISwipeGestureRecognizer alloc] 
    initWithTarget:self action:@selector(rightSwipeLineChart:)];
rightSwipe.direction = UISwipeGestureRecognizerDirectionRight;
[self.demoView addGestureRecognizer:rightSwipe];

UISwipeGestureRecognizer *leftSwipe = [[UISwipeGestureRecognizer alloc] 
    initWithTarget:self action:@selector(leftSwipeLineChart:)];
[self.demoView addGestureRecognizer:leftSwipe];

The result is I can only detect the left swipe gesture, can't detect right swipe gesture. What's wrong with my code? Thank you.

Answer

Martin_G picture Martin_G · Sep 17, 2013

The default value of UISwipeGestureRecognizer direction property is UISwipeGestureRecognizerDirectionRight so you are creating two recognizers that does the same thing.

This is how i would solve the problem:

for (int i = 0; i < 2; i++) {
    UISwipeGestureRecognizer *swipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(onGestureSwipe:)];
    swipeRecognizer.direction = (i == 0 ? UISwipeGestureRecognizerDirectionRight : UISwipeGestureRecognizerDirectionLeft);
    [self.tableView addGestureRecognizer:swipeRecognizer];
}