Previously in SwiftUI (Xcode Beta 5), a modal worked like this:
struct ContentView: View {
@State var modalIsPresented: Bool = false
var body: some View {
Button(action: {
self.modalIsPresented = true
}) {
Text("Show modal")
}
.sheet(isPresented: $modalIsPresented, content: {
ModalView()
})
}
}
struct ModalView: View {
@Environment(\.presentationMode) var presentationMode
var body: some View {
Button(action: {
self.presentationMode.value.dismiss()
}) {
Text("Hide modal")
}
}
}
But now in Xcode Beta 6, I cannot find a way to dismiss a modal. There no longer is a value
property of presentationMode
, and the other properties don't seem to have any useful methods I can use.
How do you dismiss a SwiftUI modal in Xcode Beta 6?
Modal views in SwiftUI are presented using the sheet modifier on a view or control. The simplest way is to have @State property to indicate when it should be visible. To hide the modal view, we can use the environment parameter or pass a binding to the modal view object.
SwiftUI 3 is still in beta and will become available with iOS 15 and Xcode 13. There is much more to SwiftUI 3 than can be covered here, so do not miss the What's new in SwiftUI video from WWDC 2021 if you are interested.
SwiftUI runs on iOS 13, macOS 10.15, tvOS 13, and watchOS 6, or any future later versions of those platforms. This means if you work on an app that must support iOS N-1 or even N-2 – i.e., the current version and one or two before that – then you will be limited in terms of the features you can offer.
Declarative vs Imperative Programming. Like Java, C++, PHP, and C#, Swift is an imperative programming language. SwiftUI, however, is proudly claimed as a declarative UI framework that lets developers create UI in a declarative way.
Using wrappedValue instead of value seems to work in Xcode Beta 6:
self.presentationMode.wrappedValue.dismiss()
You can dimiss .sheet
, .popover
, .actionSheet
by passing in the binding that controls it's showing, here $modalIsPresented
and set it to false inside to programmatically dismiss it.
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