NavigationLink 标记和选择未按预期工作
NavigationLink tag and selection not working as expected
我可能遗漏了一些东西,但我无法使 NavigationLink 在列表中工作。
我正在使用 NavigationLink(destination, tag, selection) 我想通过点击按钮弹出到根视图,正如您在这个示例项目中看到的那样:
import SwiftUI
struct ContentView: View {
@State var selectedView: Int? = nil
var colors: [String] = ["blue", "yellow", "green", "red", "black"]
var body: some View {
NavigationView {
List{
ForEach(colors.indices) { index in
NavigationLink(
destination: ColorDetail(selectedView: self.$selectedView, color: colors[index]),
tag: index,
selection: self.$selectedView,
label: {
Text(colors[index])
})
}
}
}
}
}
struct ColorDetail: View {
@Binding var selectedView: Int?
var color: String
var body: some View {
VStack {
Text(color)
Text("SelectedView: \(selectedView ?? 99)")
Button("set SelectedView to nil and go back") {
self.selectedView = nil
}
}
}
}
为什么我将 selectedView 设置为 nil 没有任何反应?如何在点击按钮时从 ColorDetail 弹出根视图 (ContentVIew)?
只需复制此代码并尝试,它就会构建。
正如 Asperi 所说,看起来像是 14.2 中的一个错误,因为将它设置为 nil 应该确实有效。但是,如果您需要一个适用于所有版本的解决方法,请尝试使用 presentationMode
struct ColorDetail: View {
@Binding var selectedView: Int?
var color: String
@Environment(\.presentationMode) var presentationMode
var body: some View {
VStack {
Text(color)
Text("SelectedView: \(selectedView ?? 99)")
Button("set SelectedView to nil and go back") {
self.selectedView = nil
self.presentationMode.wrappedValue.dismiss()
}
}
}
}
我可能遗漏了一些东西,但我无法使 NavigationLink 在列表中工作。
我正在使用 NavigationLink(destination, tag, selection) 我想通过点击按钮弹出到根视图,正如您在这个示例项目中看到的那样:
import SwiftUI
struct ContentView: View {
@State var selectedView: Int? = nil
var colors: [String] = ["blue", "yellow", "green", "red", "black"]
var body: some View {
NavigationView {
List{
ForEach(colors.indices) { index in
NavigationLink(
destination: ColorDetail(selectedView: self.$selectedView, color: colors[index]),
tag: index,
selection: self.$selectedView,
label: {
Text(colors[index])
})
}
}
}
}
}
struct ColorDetail: View {
@Binding var selectedView: Int?
var color: String
var body: some View {
VStack {
Text(color)
Text("SelectedView: \(selectedView ?? 99)")
Button("set SelectedView to nil and go back") {
self.selectedView = nil
}
}
}
}
为什么我将 selectedView 设置为 nil 没有任何反应?如何在点击按钮时从 ColorDetail 弹出根视图 (ContentVIew)?
只需复制此代码并尝试,它就会构建。
正如 Asperi 所说,看起来像是 14.2 中的一个错误,因为将它设置为 nil 应该确实有效。但是,如果您需要一个适用于所有版本的解决方法,请尝试使用 presentationMode
struct ColorDetail: View {
@Binding var selectedView: Int?
var color: String
@Environment(\.presentationMode) var presentationMode
var body: some View {
VStack {
Text(color)
Text("SelectedView: \(selectedView ?? 99)")
Button("set SelectedView to nil and go back") {
self.selectedView = nil
self.presentationMode.wrappedValue.dismiss()
}
}
}
}