Search code examples
iphoneuiimageviewuitouch

Setting a UIImageView with swipes


I currently use a left and right arrow to switch between images, but would like to add functionality so that the user can swipe in the direction to change the image.

How does the device detect a left swipe or right swipe and use that as an IBAction or similar to the button triggering execution?

Is there a build in method or does it need to be coded from scratch?

Thanks


Solution

  • If your target is 3.2 or higher, you can use UISwipeGestureRecognizer. Put this in your UIImageView subclass:

    - (void)viewDidLoad {
        [super viewDidLoad];
    
       UISwipeGestureRecognizer *recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(rightSwipeHandle:)];
        [recognizer setNumberOfTouchesRequired:1];
        [self addGestureRecognizer:recognizer];
        [recognizer release];
    }
    
    - (void)rightSwipeHandle:(UISwipeGestureRecognizer*)gestureRecognizer {
         //do something
    }
    

    If you're targeting 3.2 or lower, you'll need to make use of NSClassFromString & [[UIDevice currentDevice] systemVersion] to make sure the current device has the required class.