Swipe gesture in Swift 3

后端 未结 7 1217
感动是毒
感动是毒 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:04

    Swift 4, Xcode 9.2 This code will enable you to Recognize the Swipe Direction of the user on the whole ViewController (All of the iPhone screen, not specific to a button) Thanks @Ram-madhavan

    import UIKit
    
    class ViewController: UIViewController {
    
        //Label to show test and see Gesture direction. 
    
        @IBOutlet weak var swipeDirectionLabel: UILabel!
    
        override func viewDidLoad() {
            super.viewDidLoad()
          //Defining the Various Swipe directions (left, right, up, down)  
            let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(self.handleGesture(gesture:)))
            swipeLeft.direction = .left
            self.view.addGestureRecognizer(swipeLeft)
    
            let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(self.handleGesture(gesture:)))
            swipeRight.direction = .right
            self.view.addGestureRecognizer(swipeRight)
    
            let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(self.handleGesture(gesture:)))
            swipeUp.direction = .up
            self.view.addGestureRecognizer(swipeUp)
    
            let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(self.handleGesture(gesture:)))
            swipeDown.direction = .down
            self.view.addGestureRecognizer(swipeDown) 
        }
    
        //Function to Print to console Swipe Direction, and Change the label to show the directions. The @objc before func is a must, since we are using #selector (above). You can add to the function, in my case, I'll add a sound, so when someone flips the page, it plays a page sound. 
    
        @objc func handleGesture(gesture: UISwipeGestureRecognizer) -> Void {
            if gesture.direction == UISwipeGestureRecognizerDirection.right {
                print("Swipe Right")
                swipeDirectionLabel.text = "Swiped Right"
            }
            else if gesture.direction == UISwipeGestureRecognizerDirection.left {
                print("Swipe Left")
                swipeDirectionLabel.text = "Swiped Left"
    
            }
            else if gesture.direction == UISwipeGestureRecognizerDirection.up {
                print("Swipe Up")
                swipeDirectionLabel.text = "Swiped Up"
    
            }
            else if gesture.direction == UISwipeGestureRecognizerDirection.down {
                print("Swipe Down")
                swipeDirectionLabel.text = "Swiped Down"
    
            }
        }
    }
    

提交回复
热议问题