I was having issue to enable and disable swipe interaction to pop viewcontrollers.
I have a base navigation controller and my app flow is like push Splash VC, push Main VC, and then push Some VC like that.
I want swipe to go back from Some VC to Main VC. Also disable swipe to prevent going back to splash from main VC.
After some tryings below works for me.
- Write an extension in Main VC to disable swipe
extension MainViewController : UIGestureRecognizerDelegate{
func disableSwipeToPop() {
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
self.navigationController?.interactivePopGestureRecognizer?.delegate = self
}
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer == self.navigationController?.interactivePopGestureRecognizer {
return false
}
return true
}
}
- Call disableSwipeToPop() method on viewDidAppear of Main VC
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.disableSwipeToPop()
}
- Write an extension in Some VC to enable swipe to pop Some VC
extension SomeViewController{
func enableSwipeToPop() {
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
self.navigationController?.interactivePopGestureRecognizer?.delegate = nil
}
}
- Call enableSwipeToPop() method on viewDidLoad of Some VC
override func viewDidLoad() {
super.viewDidLoad()
self.enableSwipeToPop()
}
That's it. Also if you try to disable swipe on viewWillAppear, you may loose the ability to swipe again when user stops swiping to cancel the action.