In my SwiftUI app I have set in all my views .navigationBarBackButtonHidden(true)
to have always a custom Back Button, so the iOS classic swipe to go back has been disabled everywhere, but I actually need it only in specific views.
I re enabled it using this code:
extension UINavigationController: UIGestureRecognizerDelegate {
override open func viewDidLoad() {
super.viewDidLoad()
interactivePopGestureRecognizer?.delegate = self
}
public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
return viewControllers.count > 1
}
}
It works but unfortunately it re enables swipe to go back in the entire project, what should I do?
CodePudding user response:
It can be managed via some global app state, like
class AppState {
static let shared = AppState()
var swipeEnabled = false // << by default
}
extension UINavigationController: UIGestureRecognizerDelegate {
// ...
public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
return AppState.shared.swipeEnabled ?
viewControllers.count > 1 : false // << here !!
}
}
// ... and somewhere in view, for example
.onAppear {
AppState.shared.swipeEnabled = true
}
.onDisappear {
AppState.shared.swipeEnabled = false
}