How to override gesture to pop to rootViewController, not to previous ViewController?
Asked
Active
Viewed 2,531 times
1
-
1I don't think you can modify the default gesture behavior. You'll probably need to disable the default gesture and add your own gesture recognizer and transition behavior. – Greg May 22 '18 at 16:19
-
@Greg, as i thought, thanks – Ruslan Pitula May 22 '18 at 16:35
2 Answers
3
You can do this in a combination of the following:
Add a swipe gesture recognizer to your view controller:
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

telezhenkoEG1995
- 1
- 1