SwiftUI dismiss modal

前端 未结 13 2164
闹比i
闹比i 2020-11-29 23:23

Since SwiftUI is declarative there is no dismiss methode. How can is add a dismiss/close button to the DetailView?



        
13条回答
  •  情深已故
    2020-11-30 00:00

    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.
      @Environment(\.presentationMode) var 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")
          }
        }
      }
    }
    

提交回复
热议问题