只需制作
@State
非可选。然后将其转换为
Binding<String?>
使用其初始化程序之一,然后将其传递给
selection:
struct ContentView: View {
@State private var selection: String = "Finn"
var body: some View {
NavigationSplitView {
SidebarView(selection: $selection)
} detail: {
DetailView(selection: $selection)
}
}
}
struct SidebarView: View {
@Binding var selection: String
let people = ["Finn", "Leia", "Luke", "Rey"]
var body: some View {
// note the selection parameter
List(people, id: \.self, selection: Binding($selection)) { person in
Text(person)
// if you want to indicate the previously selected person more clearly
.listRowBackground(selection == person ? Color.gray : nil)
}
Text("selection = \(String(describing: selection))")
}
}
struct DetailView: View {
@Binding var selection: String
var body: some View {
Text("selectedItem = \(String(describing: selection))")
}
}
这将迫使您进行初始选择。如果你不想这样,你可以添加一个新的
状态
在里面
SidebarView
或
ContentView
.
struct SidebarView: View {
@Binding var selection: String?
@State private var visitedPerson: String?
let people = ["Finn", "Leia", "Luke", "Rey"]
var body: some View {
Group {
List(people, id: \.self, selection: $selection) { person in
Text(person)
// if you want to indicate the previously selected person more clearly
.listRowBackground(visitedPerson == person ? Color.gray : nil)
}
Text("selection = \(String(describing: visitedPerson))")
}
.onChange(of: selection) { oldValue, newValue in
if let newValue {
visitedPerson = newValue
}
}
}
}
也就是说,“强制取消选择”的行为与iOS在其他地方的行为一致。当视图被推到
List
然后弹出
列表
将不会保留其选择。
例如,请参见:
struct ContentView: View {
@State private var items = ["One", "Two", "Three"]
@State private var selected: String?
var body: some View {
NavigationStack {
List(items, id: \.self, selection: $selected) { item in
Text(item)
}
.toolbar {
NavigationLink("Navigate") {
Text("Destination")
}
}
}
}
}
你也可以比较iPhone和iPad上的设置应用程序,它也有
NavigationSplitView
-类似设计。