I am attempting to dismiss a modal view presented via a .sheet
in SwiftUI - called by a Button
which is within a NavigationView
s 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?
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.
The . navigationBarBackButtonHidden(true) will hide the back button.
Let's Start titleview in UIKit. To customize a navigation bar title view in SwiftUI, we simply set ToolbarItem of placement type . principal to a new . toolbar modifier.
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.
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