有时候我们需要让当前界面消失,可以使用以下方法:
首先声明一下显示模式:
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
然后在action区域使用:
self.presentationMode.wrappedValue.dismiss()
不过这种方法需要注意几点:
- 消失整个界面的时候,只能引出来的界面(例如NavigationView或者弹出的Alert、Sheet、Popover),不然
.presentationMode.wrappedValue.isPresented
的值是false
,自然无法dismiss()
。 - 弹出的Alert、Sheet或者Popover之类的,使用这个方法消失的是激活弹出的那个界面,而不是弹出之后的界面。
为了方便理解,下面来举个例子,假设下面这是个NavigationLink出来的二级界面,我们想让当前界面消失,就使用以下代码:
struct DismissView: View {
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var body: some View {
VStack {
Text("第二个界面")
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}, label: {
Text("消失")
})
}
}
}