1

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() 
})
Ashley Mills
  • 50,474
  • 16
  • 129
  • 160

1 Answers1

0

If you're building for iOS 16+, you can easily achieve this using a NavigationStack:

enum Router {
    case view2, view3, view4
}

struct ContentView: View {
    
    @State private var path = NavigationPath()
    
    var body: some View {
        NavigationStack(path: $path) {
            VStack {
                Text("View 1")
                NavigationLink("Show view 2", value: Router.view2)
            }
            .navigationTitle("View 1")
            .navigationDestination(for: Router.self) { router in
                switch router {
                case .view2:
                    VStack {
                        Text("View 2")
                        NavigationLink("Show view 3", value: Router.view3)
                    }
                    .navigationTitle("View 2")
                case .view3:
                    VStack {
                        Text("View 3")
                        NavigationLink("Show view 4", value: Router.view4)
                    }
                    .navigationTitle("View 3")
                case .view4:
                    VStack {
                        Text("View 4")
                        Button("Pop to view 2") {

                            // Remove from path to pop back
                            path.removeLast(2)
                        }
                    }
                    .navigationTitle("View 4")
                }
            }
        }
    }
}
Ashley Mills
  • 50,474
  • 16
  • 129
  • 160