滑动以返回特定的 SwiftUI 视图
Swipe to go back in specific SwiftUI views
在我的 SwiftUI 应用程序中,我在所有视图 .navigationBarBackButtonHidden(true)
中设置了一个自定义后退按钮,因此 iOS 经典的滑动返回已在所有地方被禁用,但我实际上需要它仅在特定视图中。
我使用此代码重新启用它:
extension UINavigationController: UIGestureRecognizerDelegate {
override open func viewDidLoad() {
super.viewDidLoad()
interactivePopGestureRecognizer?.delegate = self
}
public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
return viewControllers.count > 1
}
}
可以用,但不幸的是它重新启用了滑动返回整个项目,我该怎么办?
它可以通过一些全局应用程序状态进行管理,例如
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
}
在我的 SwiftUI 应用程序中,我在所有视图 .navigationBarBackButtonHidden(true)
中设置了一个自定义后退按钮,因此 iOS 经典的滑动返回已在所有地方被禁用,但我实际上需要它仅在特定视图中。
我使用此代码重新启用它:
extension UINavigationController: UIGestureRecognizerDelegate {
override open func viewDidLoad() {
super.viewDidLoad()
interactivePopGestureRecognizer?.delegate = self
}
public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
return viewControllers.count > 1
}
}
可以用,但不幸的是它重新启用了滑动返回整个项目,我该怎么办?
它可以通过一些全局应用程序状态进行管理,例如
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
}