在另一个课程中滑动手势识别器

时间:2018-09-05 04:00:42

标签: ios swift uigesturerecognizer

我有一个连接到第二个视图SecondViewController的ViewController,我想使用UIGesture从一个视图切换到另一个视图

class ViewController: UIViewController{

        override func viewDidLoad() {
        super.viewDidLoad()

        let svc = SecondViewController()
        let leftSwipe = UISwipeGestureRecognizer(target: svc, action: #selector(svc.swipeAction(swipe:)))
        leftSwipe.direction = UISwipeGestureRecognizerDirection.left
        self.view.addGestureRecognizer(leftSwipe)
    }
}


class SecondViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(swipeAction(swipe:)))
        rightSwipe.direction = UISwipeGestureRecognizerDirection.right
        self.view.addGestureRecognizer(rightSwipe)



        // Do any additional setup after loading the view.
    }

    @objc func swipeAction(swipe: UISwipeGestureRecognizer)
    {
        print(swipe.direction.rawValue)
        switch swipe.direction.rawValue {

        case 1:
            performSegue(withIdentifier: "toTheLeft", sender: self)
        case 2:
            performSegue(withIdentifier: "toTheRight", sender: self)
        default:
            break
        }
    }

}

代码不起作用,什么也没发生,并且我没有错误消息。

2 个答案:

答案 0 :(得分:1)

问题是svcviewDidLoad末尾超出范围,并且您的SecondViewController实例被释放。

svc设置ViewController的属性。当您希望显示第二个视图控制器时,请显示存储在svc属性中的实例。

请记住,将另一个视图控制器设置为第一个视图控制器中的手势处理程序没有什么意义。

答案 1 :(得分:0)

UISwipeGestureRecognizer的目标在两个视图控制器中都应为self,并在两个视图控制器中分别实现swipeAction