In SwiftUI
I discovered the Alert
type. But I wonder how to show it with the presentation
method.
Initializing an Alert
is pretty easy. But how to use the binding?
struct ContentView : View { var body: some View { Button(action: { // Don't know how to use the `binding` below presentation(binding, alert: { Alert(title: Text("Hello")) }) }, label: { Text("asdf") }) } }
The binding is of type Binding<Bool>
Presenting system alerts on SwiftUI is super simple. Just call an instance method alert and pass a few parameters, and you are done. But the system alerts that come up are too basic with the non-customizable default design.
1) The @State var showingPopup variable will control the displaying of the popup. 2) The only button on the screen will change the showingPopup variable state. 3) We add the popup as a modifier of our view, passing a binding for the showingPopup to control the state inside the popup implementation.
SwiftUI can't have multiple alert modifiers on the same view (the same branch in a view hierarchy, to be exact). The only latest outermost . alert will work if you got multiple alert modifiers in the same branch in a view hierarchy.
.presentation()
was actually deprecated in Beta 4. Here is a version that currently works with the .alert()
Modifier.
struct ContentView: View { @State var showsAlert = false var body: some View { Button(action: { self.showsAlert.toggle() }) { Text("Show Alert") } .alert(isPresented: self.$showsAlert) { Alert(title: Text("Hello")) } } }
You can use a @State
variable as the binding. Alternatively you can use a @EnvironmentObject
variable that uses a BindableObject
.
I think you need to call presentation
on the root View to get it to work, adding it to a Stack
, Group
, etc. doesn't seem to work.
This snippet seems to do the trick. Note that @State
variable is set to false after the alert is dismissed.
struct ContentView: View { @State var showsAlert = false var body: some View { Button(action: { self.showsAlert = true }, label: { Text("asdf") }).presentation($showsAlert, alert: { Alert(title: Text("Hello")) }) } }
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