18

I haven't been able to find a tutorial on how to properly setup a gesture recognizer for iOS. I need to detect swipe up & down, and the callbacks for them.

Any help, appreciated. Thanks.

iamruskie
  • 766
  • 4
  • 9
  • 22

2 Answers2

51

You need two recognizers, one for swiping up, and the other for swiping down:

UISwipeGestureRecognizer* swipeUpGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeUpFrom:)];
swipeUpGestureRecognizer.direction = UISwipeGestureRecognizerDirectionUp;

and for the handler:

- (void)handleSwipeUpFrom:(UIGestureRecognizer*)recognizer {

}

Finally, you add it to your view:

[view addGestureRecognizer:swipeUpGestureRecognizer];

The same for the other direction (just change all the Ups to Downs).

sergio
  • 68,819
  • 11
  • 102
  • 123
  • You are right: I was too focused on thinking that the main point for swipe recognizers is having one recognizer for direction... I added that step... – sergio Sep 14 '12 at 10:06
  • I never setup a view.. what can i put as default view or current view? also do i put all this in init method? – iamruskie Sep 14 '12 at 10:15
  • (I want it applied to the whole iPhone screen) – iamruskie Sep 14 '12 at 10:27
  • Then add it to: `[UIApplication sharedApplication].delegate.window`; since you say you do not have a view, I guess the place where to put this code is your appDidFinishLaunching... the usual place would be a `viewDidLoad` inside a view controller... – sergio Sep 14 '12 at 10:32
  • Nah, that view's not working. I was thinking more along the lines of `[[CCDirector sharedDirector] view]` or self but that doesnt work either. – iamruskie Sep 14 '12 at 10:47
  • did not get you were using Cocos2D. Use: `[[CCDirector sharedDirector].openGLView addGestureRecognizer:...`; This is what I happen to use and it works. – sergio Sep 14 '12 at 10:52
  • Okay i got it. `[[[CCDirector sharedDirector] openGLView] addGestureRecognizer:swipeUpGestureRecognizer];` – iamruskie Sep 14 '12 at 10:53
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/16688/discussion-between-david-and-sergio) – iamruskie Sep 14 '12 at 10:55
0

This worked for me in Xcode 7.3. , Swift 2.2.

import UIKit

class Viewcontroller: UIViewController
{
    override func viewDidLoad()
    {
        super.viewDidLoad()
        createAndAddSwipeGesture()
    }

    private func createAndAddSwipeGesture()
    {
        let swipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(Viewcontroller.handleSwipeLeft(_:)))
        swipeGesture.direction = UISwipeGestureRecognizerDirection.Left
        view.addGestureRecognizer(swipeGesture)
    }

    @IBAction func handleSwipeLeft(recognizer:UIGestureRecognizer)
    {
        print(" Handle swipe left...")

    }
}
MB_iOSDeveloper
  • 4,178
  • 4
  • 24
  • 36