Enable swipe back and the bug
Enable swipe back when navigation bar is hidden
In iOS, we can swipe back(left to right) to pop the view controller and navigate back. This is only available when the navigation bar is shown. If we want to swipe back even if the navigation bar is hidden, add below code at the root view.
1
2
3
4
5
6
7
override func viewDidLoad() {
super.viewDidLoad()
...
navigationController?.interactivePopGestureRecognizer?.delegate = nil
}
The bug
But be careful when using it. There is a bug, which is when we swipe back at the very root view controller. Nothing happens because there is no view controller to pop. But then, nothing happens when tapping anywhere. The view controller does not response at all. If we swipe back again, a strange view appears from the left as we swipe. After this happens, the root view controller now gets response. Below image shows the strange behavior.
To prevent this strange behavior, we need to handle the interactivePopGestureRecognizer
to be enabled or disabled. This can be in the root view controller or implement UINavigationControllerDelegate
to the root view controller. It depends on how your root view controller is structed.
1
2
3
4
5
6
7
8
9
10
11
12
// UINavigationControllerDelegate Implement
func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
interactivePopGestureRecognizer?.isEnabled = viewControllers.count > 1
}
// or the root view controller
override func viewDidAppear(_ animated: Bool) {
super.viewDidDisappear(animated)
navigationController?.interactivePopGestureRecognizer?.isEnabled = navigationController?.viewControllers.count ?? 0 > 1
}
Adding this will fix the problem. Maybe the swipe back gesture was troubling, even though the navigation controller does not have view controllers to pop. One of our apps was having some trouble about the view freezing, and we had produced this bug somehow. And it was related to this bug. Adding this code had solved the freezing bug.
Reference:
Apple Documentation
StackOverflow