Search code examples
swiftswiftuiswiftui-navigationlinkswiftui-navigationstack

How to go to different Views with with navigationDestination modifier for the NavigationStack for iOS 16?


I am trying to go to 2 differnt views from the NavigationStack by usgin differnt navigationDestination modifier, however I am always getting directed to the same destination. How to fix it?

Here is my code:

import SwiftUI

struct NavTest: View {
    var body: some View {
        
        NavigationStack {
            NavigationLink("Link1", value: "Link-1")
            NavigationLink("Link2", value: "Link-2")
                
                .navigationDestination(for: String.self) {txtValue in Link1()}
                .navigationDestination(for: String.self) {txtValue in Link2()}
        }
    }
}

struct NavTest_Previews: PreviewProvider {
    static var previews: some View {
        NavTest()
    }
}


struct Link1: View {
    var body: some View{
        Text("You are in Link1 view")
    }
}

struct Link2: View {
    var body: some View{
        Text("You are in Link2 view")
    }
}

I am aware that both my Navigation link are strings, so perhaps that's why I get redirected only to the first one, but how to modify the code so that it directs those 2 link in different views?


Solution

  • In your .navigationDestination just return a different View depending on the value of txtValue.

    .navigationDestination(for: String.self) { txtValue in
        if txtValue == "Link-1" {
            Link1()
        } else if txtValue ==  "Link-2" {
            Link2()
        }
    }
    

    However, rather than use Strings, try using an enum with a case per View to get compile time checking:

    enum Route {
        case link1, link2
    }
    
    struct ContentView: View {
            
        var body: some View {
            
            NavigationStack {
                NavigationLink("Link1", value: Route.link1)
                NavigationLink("Link2", value: Route.link2)
                    
                    .navigationDestination(for: Route.self) { route in
                        switch route {
                        case .link1:
                            Link1()
                        case .link2:
                            Link2()
                        }
                    }
            }
        }
    }