Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pop to root view via navigation stack in iOS 16

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.

like image 853
Anupam Mishra Avatar asked Sep 10 '25 18:09

Anupam Mishra


1 Answers

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()
like image 186
IamJsly Avatar answered Sep 13 '25 18:09

IamJsly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!