1.一般情况使用@Binding来绑定一个属性来修改弹窗的isPresented属性
struct DismissingView2: View {
@Binding var isPresented: Bool
var body: some View {
Button("Dismiss Me") {
isPresented = false
}
}
}
struct ContentView: View {
@State private var showingDetail = false
var body: some View {
Button("Show Detail") {
showingDetail = true
}
.sheet(isPresented: $showingDetail) {
DismissingView2(isPresented: $showingDetail)
}
}
}
现在可以包装属性@Environment来获取当前的presentationMode,它的wrappedValue就是弹窗对象,因此可以调用dismiss()方法
struct DismissingView1: View {
@Environment(\.presentationMode) var presentationMode
var body: some View {
Button("Dismiss Me") {
presentationMode.wrappedValue.dismiss()
}
}
}
struct ContentView: View {
@State private var showingDetail = false
var body: some View {
Button("Show Detail") {
showingDetail = true
}
.sheet(isPresented: $showingDetail) {
DismissingView1()
}
}
}
原文:https://www.hackingwithswift.com/quick-start/swiftui/how-to-make-a-view-dismiss-itself