我在导航视图堆栈的屏幕上的窗体中嵌入了一个选择器。我已经重新创建了一个简单的版本。
struct ContentView: View {
@State var showSecondView: Bool = false
var body: some View {
NavigationView {
VStack {
Button("SecondView", action: {
self.showSecondView = true
})
NavigationLink(destination: SecondContentView(), isActive: $showSecondView) {
EmptyView()
}
}
}
}
}
struct SecondContentView: View {
@State var showThirdView: Bool = false
var body: some View {
VStack {
Button("ThirdView", action: {
self.showThirdView = true
})
NavigationLink(destination: ThirdContentView(showThirdView: $showThirdView), isActive: $showThirdView) {
EmptyView()
}
}
}
}
struct ThirdContentView: View {
@Binding var showThirdView: Bool
@State var pickerSelection: String = ""
let pickerObjects = ["A", "B", "C"]
var body: some View {
VStack {
Form {
Picker(selection: $pickerSelection, label: Text("Abort Reason")
) {
ForEach(0 ..< pickerObjects.count) { i in
Text("\(self.pickerObjects[i])").tag(self.pickerObjects[i])
}
}
}
Button("Done", action: {
self.showThirdView.toggle()
})
}
}
}
在上面的示例中,当我设置一个值并按完成时,它导航回到第三个屏幕(带有选择器),但未选择任何值。在我的完整应用程序中,完成按钮可关闭第三个屏幕,但是当我在第二个屏幕上按回去时,它会短暂显示第三个屏幕一秒钟,然后再将其关闭。
如果我在导航链接之外显示第三个视图(如果showThirdView == true),则没有导航错误。在选择器中设置一个值似乎会将第三个视图的另一个实例添加到NavigationView堆栈中,而不是返回。我喜欢导航链接样式,因为后退按钮对用户而言是一致的。有什么方法可以使选择器在导航链接中工作?
答案 0 :(得分:1)
这是起作用的固定部件-用演示文稿模式替换了丢失的Binding。在Xcode 12 / iOS 14上进行了测试。
struct SecondContentView: View {
@State var showThirdView: Bool = false
var body: some View {
VStack {
Button("ThirdView", action: {
self.showThirdView = true
})
NavigationLink(destination: ThirdContentView(), isActive: $showThirdView) {
EmptyView()
}
}
}
}
struct ThirdContentView: View {
@Environment(\.presentationMode) var mode
@State var pickerSelection: String = ""
let pickerObjects = ["A", "B", "C"]
var body: some View {
VStack {
Form {
Picker(selection: $pickerSelection, label: Text("Abort Reason")
) {
ForEach(0 ..< pickerObjects.count) { i in
Text("\(self.pickerObjects[i])").tag(self.pickerObjects[i])
}
}
}
Button("Done", action: {
self.mode.wrappedValue.dismiss()
})
}
}
}