Gesture recognizer (swipe) on UIImageView

Sucrenoir picture Sucrenoir · Jul 29, 2013 · Viewed 40.7k times · Source

I am trying to NSLog when I swipe over an UIImageView with this code, but it does not work for some reason. Any idea ?

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIImage *image = [UIImage imageNamed:@"image2.png"];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];

    imageView.frame = [[UIScreen mainScreen] bounds];

    [self.view addSubview:imageView];

    UISwipeGestureRecognizer *recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(rightSwipeHandle:)];
    [recognizer setNumberOfTouchesRequired:1];
    [imageView addGestureRecognizer:recognizer];

}

- (void)rightSwipeHandle:(UISwipeGestureRecognizer*)gestureRecognizer {
    NSLog(@"right swipe");
}

Answer

icodebuster picture icodebuster · Jul 29, 2013

Enable UIImage view user interaction which is disabled by default.

[imageView setUserInteractionEnabled:YES];

Adding a Swipe Gesture Events

UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];

// Setting the swipe direction.
[swipeLeft setDirection:UISwipeGestureRecognizerDirectionLeft];
[swipeRight setDirection:UISwipeGestureRecognizerDirectionRight];

// Adding the swipe gesture on image view
[imageView addGestureRecognizer:swipeLeft];
[imageView addGestureRecognizer:swipeRight];

Handling Swipe Gesture Events

- (void)handleSwipe:(UISwipeGestureRecognizer *)swipe {

    if (swipe.direction == UISwipeGestureRecognizerDirectionLeft) {
        NSLog(@"Left Swipe");
    }

    if (swipe.direction == UISwipeGestureRecognizerDirectionRight) {
        NSLog(@"Right Swipe");   
    } 

}