Swipe gesture in Swift 3

后端 未结 7 1213
感动是毒
感动是毒 2020-12-07 17:33

Im trying to get a UISwipeGestureRecognizer to work in Swift 3, the default swipe right is working correctly though not up down or left.

I have tried it by control d

相关标签:
7条回答
  • 2020-12-07 18:26

    Step 1: Add swipe Gesture(s) in viewDidLoad() method.

    override func viewDidLoad() {
        super.viewDidLoad()
    
        let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(handleGesture))
        swipeLeft.direction = .left
        self.view.addGestureRecognizer(swipeLeft)
    
        let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(handleGesture))
        swipeRight.direction = .right
        self.view.addGestureRecognizer(swipeRight)
    
        let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(handleGesture))
        swipeUp.direction = .up
        self.view.addGestureRecognizer(swipeUp)
    
        let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(handleGesture))
        swipeDown.direction = .down
        self.view.addGestureRecognizer(swipeDown)
    }
    

    Step 2: Check the gesture detection in handleGesture() method

    func handleGesture(gesture: UISwipeGestureRecognizer) -> Void {
       if gesture.direction == .right {
            print("Swipe Right")
       }
       else if gesture.direction == .left {
            print("Swipe Left")
       }
       else if gesture.direction == .up {
            print("Swipe Up")
       }
       else if gesture.direction == .down {
            print("Swipe Down")
       }
    }
    

    I hope this will help someone.

    UPDATE:

    You need to use @objc to call your 'Selector' method for latest swift versions. ie,

    @objc func handleGesture(gesture: UISwipeGestureRecognizer) -> Void {
      .
      .
      .
    }
    
    0 讨论(0)
提交回复
热议问题