func callAsFunction ()
Overview 概要
Use the dismiss
environment value to get the instance of this structure for a given Environment
. Then call the instance to perform the dismissal. You call the instance directly because it defines a call
method that Swift calls when you call the instance.
For example, you can create a button that calls the Dismiss
:
private struct SheetContents: View {
private var dismiss (\.dismiss)
var body: some View {
Button("Done") {
dismiss()
}
}
}
If you present the Sheet
view in a sheet, the user can dismiss the sheet by tapping or clicking the sheet’s button:
private struct DetailView: View {
private var isSheetPresented = false
var body: some View {
Button("Show Sheet") {
isSheetPresented = true
}
.sheet(isPresented: $isSheetPresented) {
SheetContents()
}
}
}
Be sure that you define the action in the appropriate environment. For example, don’t reorganize the Detail
in the example above so that it creates the dismiss
property and calls it from the sheet(item:
view modifier’s content
closure:
private struct DetailView: View {
private var isSheetPresented = false
private var dismiss // Applies to DetailView. (\.dismiss)
var body: some View {
Button("Show Sheet") {
isSheetPresented = true
}
.sheet(isPresented: $isSheetPresented) {
Button("Done") {
dismiss() // Fails to dismiss the sheet.
}
}
}
}
If you do this, the sheet fails to dismiss because the action applies to the environment where you declared it, which is that of the detail view, rather than the sheet. In fact, if you’ve presented the detail view in a Navigation
, the dismissal pops the detail view from the navigation stack.
The dismiss action has no effect on a view that isn’t currently presented. If you need to query whether SwiftUI is currently presenting a view, read the is
environment value.