Search code examples
iosswiftswiftuicombine

How to Access the objects from NavigationStack in SWIFTUI? I am using iOS 16 NavigationStack


I want to go from View PathD to PathB in the NavigationStack withOut creating a new Object of PathB and also not removing the view instance of PathC that is in the Navigation Stack Hierarchy.

Details:

@State var path: [String] = []

// or this can also be written
//@State var path: NavigationPath = NavigationPath()

var body: some View {
        NavigationStack(path: $path) {
            ZStack{         
                Text("SomeThing")
            }
            .navigationDestination(for: String.self, destination: { path in 
                switch path {      
                case "pathA" :
                   PathA().navigationBarBackButtonHidden()
                case "pathB":
                    PathB().navigationBarBackButtonHidden()
                case "pathC":
                    PathC().navigationBarBackButtonHidden()
                default:
                    PathD().navigationBarBackButtonHidden()
                }
            })

here what I tried is matching the reference name when navigation is done in some view

 path.append("pathA")

now consider I am in view PathD(). And I want to navigate back to PathB. one option is to slide around but I am disabling the navigation back button.

so what I do is

from PathD

path.append("pathB")

This will create a new PathB() view instead of returning to the one I have.

Now my requirement is to go back to the PathB() that I created and not a new object.

feel free to comment if my explanation is not sufficient


Solution

  • In iOS < 16.0 you can use PresentationMode to dismiss the current view and return to previous, i.e. "navigate back":

    // Auto-injected environment variable (no need to manually .environment it)
    @Environment(\.presentationMode) var mode: Binding<PresentationMode>
    
    func navigateBack() { mode.wrappedValue.dismiss() }
    

    For iOS 16 onwards, this has been replaced by isPresented and dismiss. The latter can be used for an equivalent "navigate back".

    private struct SheetContents: View {
        @Environment(\.dismiss) private var dismiss
    
        var body: some View {
            Button("Go to Previous View") {
                dismiss()
            }
        }
    }
    

    I've written some helper functions for the new Navigation system here, which you may find useful.