1

How to override gesture to pop to rootViewController, not to previous ViewController?

Gaurav Patel
  • 532
  • 1
  • 5
  • 19
Ruslan Pitula
  • 53
  • 1
  • 11

2 Answers2

3

You can do this in a combination of the following:

Add a swipe gesture recognizer to your view controller:

enter image description here

Add the following to your view controller class:

import UIKit

class SwipeBackViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        navigationController?.interactivePopGestureRecognizer?.isEnabled = false
    }

    @IBAction func swipeback(_ sender: UISwipeGestureRecognizer) {
        navigationController?.popToRootViewController(animated: true)
    }
}
  • The command in viewDidLoad disables the default swipe recogninzer in iOS
  • Then, the action associated with the swipe recognizer you added above handles the pop for you

My answer here goes into disabling the recognizer in more detail in case you have any questions on that.

CodeBender
  • 35,668
  • 12
  • 125
  • 132
0

Also, you can set delegate of this gesture in viewController, in viewController's viewDidLoad. It looks like :

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationController.interactivePopGestureRecognizer?.delegate = self
    }

and customize it's methods in view controller. For example:

       func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive event: UIEvent) -> Bool {
        print("event \(event.description)")
        return true
   }

If you set returning value for false - pop action will not be triggered

For me it worked like :

    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive event: UIEvent) -> Bool {
        showAlertViewController()
        return false
   }

If you need this behaviour only once, you should set delegate back in viewController's deinit method

    deinit {
        navigationController?.interactivePopGestureRecognizer?.delegate = navigationController
    } 
cutiko
  • 9,887
  • 3
  • 45
  • 59