2

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?

Pro Girl
  • 762
  • 7
  • 21

1 Answers1

2

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