'Overriding back swipe gesture in UINavigationController

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



Solution 1:[1]

I followed CodeBender's answer but the swipeback function didn't call.

After add self.view.addGestureRecognizer(backswipeGestureRecognizer) in viewDidLoad(), it works.

Solution 2:[2]

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
} 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SeungWoo-Ryu
Solution 2 telezhenkoEG1995