Since SwiftUI is declarative there is no dismiss
methode.
How can is add a dismiss/close button to the DetailView
?
struct DetailView: View {
var body: some View {
Text("Detail")
}
}
struct ContentView : View {
var body: some View {
PresentationButton(Text("Click to show"), destination: DetailView())
}
}
You can use
presentationMode
environment variable in your modal view and callingself.presentaionMode.wrappedValue.dismiss()
to dismiss the modal:Seems that for Xcode 11 Beta 7 (this is on build 11M392r of Xcode) it's slightly different.
In Xcode 11.0 beta 7, the value is now wrapped, the following function is working for me:
The modal views in SwiftUI seem to be simple until you start using them in a
List
orForm
views. I have created a small library which wraps all the edge cases and makes the using of modal views the same asNavigationView
-NavigationLink
pair.The library is open-sourced here: https://github.com/diniska/modal-view. You can include it into the project using Swift Package Manager, or just by copying the single file that the library includes.
The solution for your code would be:
Additionally, there is an article with full description and examples: How to present modal view in SwiftUI
There is now a pretty clean way to do this in Beta 5.
Since
PresentationButton
is easy to use but hiding the state wich is undermining the predictive character ofSwiftUI
I have implemented it with an accessibleBinding
.This is how it is used: