As we know Apple have introduced NavigationStack
in SwiftUI available from iOS16.*
Let say I have created ViewA, ViewB, ViewC, ViewD
And now I have navigated like ViewA->ViewB->ViewC->ViewD
Now I am looking to pop to root view i.e on ViewA
from ViewD
Any help would be appreciated.
This worked for me but I can't find the url so I will just share the code. You can also try it out...
Create a file and add the following;
import Foundation
struct NavigationUtil {
static func popToRootView() {
DispatchQueue.main.asyncAfter(deadline: .now()) {
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 call this from anywhere in your code;
NavigationUtil.popToRootView()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With