Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!

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

New member
Joined
Feb 7, 2023
Messages
5
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:

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?
 
New member
Joined
Feb 7, 2023
Messages
14
In your .navigationDestination just return a different View depending on the value of txtValue.

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

Rather than use Strings, try using an enum with a case per View, e.g.

Code:
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()
                    }
                }
        }
    }
}
 
Top