On iOS 14 and earlier, we import the presentationMode
environment variable:
@Environment(\.presentationMode) var presentationMode
and then call self.presentationMode.wrappedValue.dismiss()
to dismiss the view.
This has been deprecated on iOS 15, and a new environment variable, dismiss
, is introduced:
@Environment(\.dismiss) var dismiss
which we can call directly using dismiss()
to achieve the same.
I know we can do the following to call the appropriate dismiss function and support all versions:
if #available(iOS 15, *) {
self.dismiss()
} else {
self.presentationMode.wrappedValue.dismiss()
}
But how do I import/define the right environment variable? As trying this doesn't work:
if #available(iOS 15, *) {
@Environment(\.dismiss) var dismiss
} else {
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
}
Edit:
Apparently using presentationMode
to dismiss a view in a Navigation stack still works on iOS 15 Beta 4. Unless there is a TabView inside the NavigationView:
struct ContentView: View {
var body: some View {
NavigationView {
TabView {
NavigationLink(destination: ChildView()) {
Text("View Child")
}
}
}
}
}
struct ChildView: View {
@Environment(\.presentationMode) var presentationMode
var body: some View {
Button(action: {
print("Popping...")
self.presentationMode.wrappedValue.dismiss()
}, label: {
Text("POP")
.font(.headline)
})
}
}
presentatinMode
doesn't work in this case.
To support dismiss and iOS 14 add this extension to your EnvironmentValues
@available(iOS 14.0, *)
extension EnvironmentValues {
var dismiss: () -> Void {
{ presentationMode.wrappedValue.dismiss() }
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With