Reputation: 530
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).
The desired behaviour on startup is:
Upvotes: 1
Views: 1771
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