bapafes482
bapafes482

Reputation: 530

How to set NavigationView default value?


I have the following code:

import SwiftUI


struct DetailView: View {
    let text: String

    var body: some View {
        Text(text)
            .frame(maxWidth: .infinity, maxHeight: .infinity)
    }
}


struct ContentView: View {
    private let names = ["One", "Two", "Three"]
    @State private var selection: String? = "One"

    var body: some View {
        NavigationView {
            List(selection: $selection) {
                ForEach(names, id: \.self) { name in
                    NavigationLink(destination: DetailView(text: name)) {
                        Text(name)
                    }
                }
            }

            DetailView(text: "Make a selection")
        }
    }
}


struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

I thought that setting 'selection' to 'One' is the answer but it only makes 'One' highlighted (with grey color by the way). enter image description here

The desired behaviour on startup is: enter image description here

Upvotes: 1

Views: 1771

Answers (1)

93sauu
93sauu

Reputation: 4107

It should work adding the selection in the placeholder selection ?? "Make a selection", i.e:

struct ContentView: View {
    private let names = ["One", "Two", "Three"]
    @State private var selection: String? = "One"

    var body: some View {
        NavigationView {
            List(selection: $selection) {
                ForEach(names, id: \.self) { name in
                    NavigationLink(destination: DetailView(text: name)) {
                        Text(name)
                    }
                }
            }

            DetailView(text: selection ?? "Make a selection")
        }
    }
}

Upvotes: 2

Related Questions