3

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?

1 Answer 1

3

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()
                    }
                }
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.