How to dismiss SwiftUI modal view
Download materialsVery often we present a SwiftUI view modally using sheet modifier, or by pushing it onto the navigation stack. In order to dismiss it, you can use presentationMode environment value:
struct SettingsScreen: View {
@Environment(\.presentationMode) var presentationMode
var body: some View {
NavigationView {
Text("Hello, World!")
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button("Dismiss") {
presentationMode.wrappedValue.dismiss()
}
}
}
}
}
}
The benefit of this approach is that it works both for navigation stacks and for modal sheets. It also works when we present SwiftUI view embedded into a UIHostingController from UIKit context.
The environment value presentationMode works from iOS 12.0, but since iOS 15.0 we have a new, direct API to dismiss views which is dismiss environment value:
@available(iOS 15.0, *)
struct SettingsScreen: View {
@Environment(\.dismiss) var dismiss
var body: some View {
NavigationView {
Text("Hello, World!")
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button("Dismiss") {
dismiss()
}
}
}
}
}
}
Task Flow: Task Manager App
Task Flow offers innovative features like multi-project tasks and the 'My Task Flow' concept. On top of the project structure, you get an endlessly flexible Task Flow view that suits the way you think and work. Available on iPhone, iPad, Mac and Apple Vision.
Try it now!
Conclusion
Dismissing views in SwiftUI is very simple thanks to the environment values presentationMode and dismiss. I hope you found this article helpful. If you have any questions, suggestions, or feedback, please let me know on Twitter.
You can download a sample project with the implementation via the link at the top of the page.
Thanks for reading!