问题描述
在以下示例中,我有一个视图显示一张 ViewOne
。 ViewOne
有一个 NavigationLink
到 ViewTwo
。
如何从 ViewTwo
关闭工作表?
使用 presentationMode.wrappedValue.dismiss()
导航回 ViewOne
。
struct ContentView: View {
@State private var isShowingSheet = false
var body: some View {
Button("Show sheet",action: {
isShowingSheet.toggle()
})
.sheet(isPresented: $isShowingSheet,content: {
ViewOne()
})
}
}
struct ViewOne: View {
var body: some View {
NavigationView {
NavigationLink("Go to ViewTwo",destination: ViewTwo())
.isDetailLink(false)
}
}
}
struct ViewTwo: View {
@Environment(\.presentationMode) var presentationMode
var body: some View {
Button("dismiss sheet here") {
presentationMode.wrappedValue.dismiss()
}
}
}
解决方法
这可能取决于平台 - 例如,在 macOS 上的 NavigationView
中,您现有的代码有效。
将 Binding
显式传递给原始工作表状态应该可以工作:
struct ContentView: View {
@State private var isShowingSheet = false
var body: some View {
Button("Show sheet",action: {
isShowingSheet.toggle()
})
.sheet(isPresented: $isShowingSheet,content: {
ViewOne(showParentSheet: $isShowingSheet)
})
}
}
struct ViewOne: View {
@Binding var showParentSheet : Bool
var body: some View {
NavigationView {
NavigationLink("Go to ViewTwo",destination: ViewTwo(showParentSheet: $showParentSheet))
//.isDetailLink(false)
}
}
}
struct ViewTwo: View {
@Binding var showParentSheet : Bool
@Environment(\.presentationMode) var presentationMode
var body: some View {
Button("Dismiss sheet here") {
showParentSheet = false
}
}
}