View1 -> View2 -> View3 -> View4
How can I pop from View4 directly to View2 considering that we do not have control over the navigation stack ?
I try to Pop to the Root View in a SwiftUI NavigationView.
Add a helper to your SwiftUI App
import UIKit
struct NavigationUtil {
static func popToRootView() {
findNavigationController(viewController: UIApplication.shared.windows.filter { $0.isKeyWindow }.first?.rootViewController)?
.popToRootViewController(animated: true)
}
static func findNavigationController(viewController: UIViewController?) -> UINavigationController? {
guard let viewController = viewController else {
return nil
}
if let navigationController = viewController as? UINavigationController {
return navigationController
}
for childViewController in viewController.children {
return findNavigationController(viewController: childViewController)
}
return nil
}
}
Then just call the popToRootView function
Button("Pop to Root", action: {
NavigationUtil.popToRootView()
})