How to set NavigationView default value?

本小妞迷上赌 提交于 2021-01-29 10:13:28

问题



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:


回答1:


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")
        }
    }
}


来源:https://stackoverflow.com/questions/59637046/how-to-set-navigationview-default-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!