Since SwiftUI is declarative there is no dismiss
method. 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()) } }
The first option is to tell the view to dismiss itself using its presentation mode environment key. Any view can read its presentation mode using @Environment(\. presentationMode) , and calling wrappedValue. dismiss() on that will cause the view to be dismissed.
In SwiftUI. Use SheetKit to dismiss all sheets with animation controll.
An indication whether a view is currently presented by another view.
SwiftUI provides the interactiveDismissDisabled() modifier to control whether the user can swipe downwards to dismiss a sheet.
struct ContentView: View { @State private var showModal = false var body: some View { Button("Show Modal") { self.showModal.toggle() }.sheet(isPresented: $showModal) { ModalView(showModal: self.$showModal) } } } struct ModalView: View { @Binding var showModal: Bool var body: some View { Text("Modal view") Button("Dismiss") { self.showModal.toggle() } } }
You can use presentationMode
environment variable in your modal view and calling self.presentaionMode.wrappedValue.dismiss()
to dismiss the modal:
struct ContentView: View { @State private var showModal = false // If you are getting the "can only present once" issue, add this here. // Fixes the problem, but not sure why; feel free to edit/explain below. @SwiftUI.Environment(\.presentationMode) private var presentationMode: Binding<PresentationMode> var body: some View { Button(action: { self.showModal = true }) { Text("Show modal") }.sheet(isPresented: self.$showModal) { ModalView() } } } struct ModalView: View { @Environment(\.presentationMode) private var presentationMode var body: some View { Group { Text("Modal view") Button(action: { self.presentationMode.wrappedValue.dismiss() }) { Text("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