Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to present an Alert with swiftUI

Tags:

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>

like image 321
Lukas Würzburger Avatar asked Jun 04 '19 17:06

Lukas Würzburger


People also ask

How do I present a custom alert in SwiftUI?

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.

How do I show popup in SwiftUI?

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.

How do I show multiple alerts in SwiftUI?

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.


2 Answers

.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"))         }     } } 
like image 118
thisIsTheFoxe Avatar answered Sep 21 '22 18:09

thisIsTheFoxe


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"))         })     } } 
like image 39
tsp Avatar answered Sep 20 '22 18:09

tsp