Change iOS view / view controller using swipe gesture

24.4k views Asked by At

How can I implement a swipe gesture to change view to and fro?

The best example I've seen so far is the Soundcloud application but I couldn't figure out how to make it work.

4

There are 4 answers

0
Youssef Gamal On

You can a UISwipeGestureRecognizer to your UIView and add to this gesture a target and an action to perform when the gesture occurs

 var swipeGesture = UISwipeGestureRecognizer(target: self, action: "doSomething")
 myView.addGestureRecognizer(swipeGesture)

 func doSomething() {

    // change your view's frame here if you want        
 }
0
BevTheDev On

This tutorial might be helpful to you: http://www.avocarrot.com/blog/implement-gesture-recognizers-swift/

Basically, you'll need to add a gesture recognizer to your view that listens for swipe gestures. Then when it detects a swipe, push to the next view.

0
nachshon f On

Use this code...

override func viewDidLoad() {
    super.viewDidLoad()

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


}

func respondToSwipeGesture(gesture: UIGestureRecognizer) {

    if let swipeGesture = gesture as? UISwipeGestureRecognizer {

        switch swipeGesture.direction {

        case UISwipeGestureRecognizerDirection.Right:

            println("Swiped right")

//change view controllers

    let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

        let resultViewController = storyBoard.instantiateViewControllerWithIdentifier("StoryboardID") as ViewControllerName

        self.presentViewController(resultViewController, animated:true, completion:nil)    



        default:
            break
        }
    }
}
1
Essam Fahmy On

Compatible with Swift 5

override func viewDidLoad()
{
    super.viewDidLoad()

    let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipes(_:)))
    let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipes(_:)))
    
    leftSwipe.direction = .left
    rightSwipe.direction = .right

    view.addGestureRecognizer(leftSwipe)
    view.addGestureRecognizer(rightSwipe)
}

@objc func handleSwipes(_ sender: UISwipeGestureRecognizer)
{
    if sender.direction == .left
    {
       print("Swipe left")
       // show the view from the right side
    }

    if sender.direction == .right
    {
       print("Swipe right")
       // show the view from the left side
    }
}