Search code examples
iosswiftuiswipegesturerecognizer

How do I make my UISwipeGestureRecognizer work?


I have a UIGestureRecognizer that I want to recognize when the user swipes right and down and printl "swiped right" and "swiped down". I've tried a lot of different things, but I still can't get it to work. Can someone tell me what the problem is with my code?

@IBAction func respondToSwipeGesture(sender: UISwipeGestureRecognizer) {

        if let swipeGesture = sender as? UISwipeGestureRecognizer {

            switch swipeGesture.direction {
            case UISwipeGestureRecognizerDirection.Right:
                println("Swiped right")
            case UISwipeGestureRecognizerDirection.Down:
                println("Swiped down")
            default:
                break
            }
        }
    }

override func viewDidLoad() {
        super.viewDidLoad()

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

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

Solution

  • Try

     //do not need IBAction here
     func respondToSwipeGesture(sender: UISwipeGestureRecognizer) {
        switch sender.direction {//Do not need to optional cast here
        case UISwipeGestureRecognizerDirection.Right:
            println("Swiped right")
        case UISwipeGestureRecognizerDirection.Down:
            println("Swiped down")
        default:
            break
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        var swipeRight = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:")
        swipeRight.direction = UISwipeGestureRecognizerDirection.Right
        self.view.addGestureRecognizer(swipeRight)
    
        var swipeDown = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:")
        swipeDown.direction = UISwipeGestureRecognizerDirection.Down
        self.view.addGestureRecognizer(swipeDown)
        self.view.userInteractionEnabled = true //Here need to be true
    }
    

    It works well on my simulator enter image description here