TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: NavigationLink inside ForEach?

Forums > SwiftUI

Basically, I'm trying to put a list of names from an array into a list, and then have each one of those list items pass to another view. I'll include a code example below to illustrate the problem, and how I've (clearly incorrectly) gone about it. Hopefully someone can explain where I'm going wrong, and a better solution!

Many thanks!

struct test: View {
    @State private var array: [String] = ["John", "Adam"]
    var body: some View {
        NavigationView {
        List {
            ForEach(array, id: \.self) {
                NavigationLink(destination: Text("Second view")) {
                Text($0)
                }
            }
        }
        .navigationTitle("test")
        }

    }
}

3      

Change:

ForEach(array, id: \.self) {
    NavigationLink(destination: Text("Second view")) {
        Text($0)
    }
}

to:

ForEach(array, id: \.self) { name in
    NavigationLink(destination: Text("Second view")) {
        Text(name)
    }
}

4      

Thank you!

4      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.