如何使我的UISwipeGestureRecognizer工作?

时间:2015-06-03 14:03:13

标签: ios swift uiswipegesturerecognizer

当用户向右和向下滑动并UIGestureRecognizer“向右滑动”和“向下滑动”时,我想要识别printl。我尝试了很多不同的东西,但我仍然无法让它发挥作用。有人能告诉我我的代码有什么问题吗?

@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)

1 个答案:

答案 0 :(得分:1)

尝试

 //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
}

它在我的模拟器上运行良好 enter image description here