In this article, we will look at dismiss environment value, which is used to perform dismissal of current view.
dismiss environment value is the way to get the instance of DismissAction instance which is an environment value.
dismiss is available for iOS 15 and above.
Let’s look at an example for this. We will start with a simple view, which contains a State property to control display of sheet. This State variable will be toggled using a button and when it’s true, a sheet will be presented. Sheet’s content will have DetailView which will be dismissed using dismiss environment variable.
struct ContentView: View {
@State private var showSheet = false
var body: some View {
NavigationStack {
VStack {
Text("DevTechie")
.font(.largeTitle)
.foregroundColor(.orange)
Button {
showSheet.toggle()
} label: {
Label("Show Sheet", systemImage: "square.and.arrow.up.fill")
}
.buttonStyle(.bordered)
.sheet(isPresented: $showSheet) {
DetailView()
}
}
}
}
}
Our DetailView will have Environment variable with key path to \.dismiss this key path will be mapped to a variable called dismiss and we will call this as a function to close the sheet view.
struct DetailView: View {
@Environment(\.dismiss) var dismiss
var body: some View {
VStack {
Text("Hello again DevTechie!")
.font(.title)
.foregroundColor(.primary)
Text("Welcome to the detail view :)")
.font(.body)
.foregroundColor(.secondary)
Button {
dismiss()
} label: {
Label("Close", systemImage: "xmark")
}
.buttonStyle(.bordered)
}
}
}
Note: be sure to call dismiss from the view which you want to dismiss not from the view which is the presenter.With that we have reached the end of this article. Thank you once again for reading. Don’t forget to follow 😍. Also subscribe our newsletter at https://www.devtechie.com