Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change iOS view / view controller using swipe gesture

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.

like image 549
Xpx Avatar asked Jun 16 '15 18:06

Xpx


People also ask

How do I switch between view controllers?

Right-click the control or object in your current view controller. Drag the cursor to the view controller you want to present. Select the kind of segue you want from the list that Xcode provides.

What is swipe gesture on iPhone?

Swipe right or left along the bottom edge of the screen to quickly switch between open apps. See Switch between open apps on iPhone.

How do I use swipe gesture recognizer in Swift?

A swipe gesture recognizer detects swipes in one of four directions, up , down , left , and right . We set the direction property of the swipe gesture recognizer to down . If the user swipes from the top of the blue view to the bottom of the blue view, the swipe gesture recognizer invokes the didSwipe(_:)


2 Answers

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
    }
}
like image 77
Essam Fahmi Avatar answered Nov 09 '22 12:11

Essam Fahmi


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
        }
    }
}
like image 45
nachshon f Avatar answered Nov 09 '22 14:11

nachshon f