problème0123
problème0123

Reputation: 871

swipe gesture recognizer in another class

I have a ViewController that is connected to a second view SecondViewController and I would like to switch from one to another with a 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
        }
    }

}

The code does not work, nothing happens and I have no error message.

Upvotes: 1

Views: 124

Answers (2)

rmaddy
rmaddy

Reputation: 318944

The problem is that svc goes out of scope at the end of viewDidLoad and your instance of SecondViewController gets deallocated.

Make svc a property of ViewController. When you wish to display the second view controller, display the instance stored in the svc property.

Keep in mind that it makes little sense to setup another view controller as the handler for a gesture in the first view controller.

Upvotes: 1

Ricky Mo
Ricky Mo

Reputation: 7718

the target of the UISwipeGestureRecognizer should be self in both view controller, and implement swipeAction separately in both view controller.

Upvotes: 0

Related Questions