10

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.

pkamb
  • 33,281
  • 23
  • 160
  • 191
Xpx
  • 137
  • 1
  • 2
  • 7

4 Answers4

12

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
    }
}
Essam Fahmi
  • 1,920
  • 24
  • 31
  • @Possible if you don't mind can look my swipe gesture issue .. its related to change data and I am not getting an idea how to implement. https://stackoverflow.com/questions/59116225/how-can-i-implement-swipe-left-and-right-to-change-data-views-in-swift-ios – Newbie Nov 30 '19 at 14:42
10

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
        }
    }
}
nachshon f
  • 3,540
  • 7
  • 35
  • 67
2

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

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.

BevTheDev
  • 563
  • 2
  • 9