Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI dismiss modal

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())   } } 
like image 972
Ugo Arangino Avatar asked Jun 09 '19 18:06

Ugo Arangino


People also ask

How do I dismiss a modal SwiftUI?

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.

How do I dismiss all sheets in SwiftUI?

In SwiftUI. Use SheetKit to dismiss all sheets with animation controll.

What is presentationMode in SwiftUI?

An indication whether a view is currently presented by another view.

How do you prevent a sheet from being dismissed with a swipe?

SwiftUI provides the interactiveDismissDisabled() modifier to control whether the user can swipe downwards to dismiss a sheet.


1 Answers

Using @State property wrapper (recommended)

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()         }     } } 

Using presentationMode

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")       }     }   } } 

enter image description here

like image 191
M Reza Avatar answered Sep 28 '22 09:09

M Reza