How to override gesture to pop to rootViewController, not to previous ViewController?
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)
}
}
viewDidLoad
disables the default swipe recogninzer in iOS My answer here goes into disabling the recognizer in more detail in case you have any questions on that.
I followed CodeBender's answer but the swipeback
function didn't call.
After add self.view.addGestureRecognizer(backswipeGestureRecognizer)
in viewDidLoad()
, it works.
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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.