SwiftUI dismiss modal sheet presented from Navigat

2020-06-06 02:49发布

问题:

I am attempting to dismiss a modal view presented via a .sheet in SwiftUI - called by a Button which is within a NavigationViews navigationBarItems, as per below:

struct ModalView : View {

    @Environment(\.presentationMode) var presentationMode  

    var body: some View {       
        Button(action: {
            self.presentationMode.value.dismiss()
        }, label: { Text("Save")})
    }   

}

struct ContentView : View {

    @State var showModal: Bool = false

    var body: some View {
         NavigationView { 
           Text("test")
           .navigationBarTitle(Text("Navigation Title Text"))
           .navigationBarItems(trailing:
               Button(action: {
                   self.showModal = true
               }, label: { Text("Add") })
                   .sheet(isPresented: $showModal, content: { ModalView() })
           )
        }
    }

}

The modal does not dismiss when the Save button is tapped, it just remains on screen. The only way to get rid of it is swiping down on the modal.

Printing the value of self.presentationMode.value always shows false so it seems to think that it hasn't been presented.

This only happens when it is presented from the NavigationView. Take that out and it works fine.

Am I missing something here, or is this a beta issue?

回答1:

You need to move the .sheet outside the Button.

NavigationView {
  Text("test")
  .navigationBarTitle(Text("Navigation Title Text"))
  .navigationBarItems(trailing:
     Button("Add") {
       self.showModal = true
     }
  )
  .sheet(isPresented: $showModal, content: { ModalView() })
}

You can even move it outside the NavigationView closure.

NavigationView {
  Text("test")
  .navigationBarTitle(Text("Navigation Title Text"))
  .navigationBarItems(trailing:
     Button("Add") { self.showModal = true }
  )
}
.sheet(isPresented: $showModal, content: { ModalView() })

Notice you can also simplify the Button call if you have a simple text button.



标签: swiftui