Question

In my iPhone app, I require to recognize the swipe gesture made by the user on the view.

I want the swipe gestures to be recognized and perform a function on swipe.

I need that the view should horizontally slide and show another view as a user makes a swipe gesture.

What needs to be done?

How do I recognize it?

Was it helpful?

Solution

Use the UISwipeGestureRecognizer. Not much else to say really, gesture recognizers are easy. There are WWDC10 videos on the subject even. Sessions 120 and 121. :)

OTHER TIPS

If You know how it works, but still need a quick example, here it is! (it will become handy at least for me, when I will need copy-paste example, without trying remembering it)

UISwipeGestureRecognizer *mSwipeUpRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(doSomething)];

[mSwipeUpRecognizer setDirection:(UISwipeGestureRecognizerDirectionUp | UISwipeGestureRecognizerDirectionDown | UISwipeGestureRecognizerDirectionLeft | UISwipeGestureRecognizerDirectionRight)];

[[self view] addGestureRecognizer:mSwipeUpRecognizer];

and in .h file add:

<UIGestureRecognizerDelegate>

The following link below redirects you to a video tutorial which explains you how to detect swipes on the iPhone in Objective-C:

UISwipeGestureRecognizer Tutorial (Detecting swipes on the iPhone)

Code sample below, to achieve that in Swift:

You need to have one UISwipeGestureRecognizer for each direction. It's a little weird because the UISwipeGestureRecognizer.direction property is an options-style bit mask, but each recognizer can only handle one direction. You can send them all to the same handler if you want, and sort it out there, or send them to different handlers. Here's one implementation:

override func viewDidLoad() {
    super.viewDidLoad()

    var swipeRight = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:")
    swipeRight.direction = UISwipeGestureRecognizerDirection.Right
    self.view.addGestureRecognizer(swipeRight)

    var swipeDown = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:")
    swipeDown.direction = UISwipeGestureRecognizerDirection.Down
    self.view.addGestureRecognizer(swipeDown)
}

func respondToSwipeGesture(gesture: UIGestureRecognizer) {

    if let swipeGesture = gesture as? UISwipeGestureRecognizer {

        switch swipeGesture.direction {
        case UISwipeGestureRecognizerDirection.Right:
            println("Swiped right")
        case UISwipeGestureRecognizerDirection.Down:
            println("Swiped down")
        default:
            break
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top