Brandon Bradley
Brandon Bradley

Reputation: 3378

Multiple NavigationLink in SwiftUI

Can you have multiple NavigationLinks in SwiftUI? The following only displays the first Link:

struct Test : View {
    var body: some View {
        NavigationView {
            NavigationLink(destination: Text("First")) {
                Text("Visible")
            }
            NavigationLink(destination: Text("Second")) {
                Text("Invisible")
            }
            //EDIT: Also Invisible
            Text("Not rendered")
        }
    }
}

EDIT: Turns out everything under the first NavigationLink is not displayed

Upvotes: 6

Views: 8184

Answers (3)

ingconti
ingconti

Reputation: 11636

see apple example, that has a clean impelementation. Here: https://developer.apple.com/documentation/swiftui/navigationlink

If You need to

  1. add navigation on buttons, You have simply to set a state var un button action, (button will be where You put Text("xxvisible") ), say it selection.

  2. in Apple code:

    ...

    detail: { if let color = selection { ColorDetail(color: color) } else { Text("Pick a color") } }

replace color with Your selection and use else or switch/case.

Upvotes: 1

sachin jeph
sachin jeph

Reputation: 209

Look you can definitely have multiple NavigationLinks but here you are doing one things wrong.

The body property returns a single View but here you are trying to return more than one views, which causes the error.

To Solve this issue we put them inside another View like a VStack or a HStack, like shown above in the answer given by kontiki.

Upvotes: 2

kontiki
kontiki

Reputation: 40499

Put your views inside a VStack:

struct Test : View {
    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(destination: Text("First")) {
                    Text("Visible")
                }

                NavigationLink(destination: Text("Second")) {
                    Text("Invisible")
                }
                //EDIT: Also Invisible
                Text("Not rendered")
            }
        }
    }
}

Upvotes: 10

Related Questions