我可能遗漏了一些东西,但我无法让 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)?
只需复制此代码并尝试它,它就会构建。