Proper Swipe gesture recognizer iOS
Asked Answered
O

2

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.

Olid answered 14/9, 2012 at 9:49 Comment(0)
A
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).

Acquisitive answered 14/9, 2012 at 9:55 Comment(8)
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...Acquisitive
I never setup a view.. what can i put as default view or current view? also do i put all this in init method?Olid
(I want it applied to the whole iPhone screen)Olid
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...Acquisitive
Nah, that view's not working. I was thinking more along the lines of [[CCDirector sharedDirector] view] or self but that doesnt work either.Olid
did not get you were using Cocos2D. Use: [[CCDirector sharedDirector].openGLView addGestureRecognizer:...; This is what I happen to use and it works.Acquisitive
Okay i got it. [[[CCDirector sharedDirector] openGLView] addGestureRecognizer:swipeUpGestureRecognizer];Olid
let us continue this discussion in chatOlid
I
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...")

    }
}
Intrust answered 1/4, 2016 at 9:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.