Reputation: 1369
In the following simple example, why is Alert 2 not showing up?
struct ContentView: View {
@State private var showingOtherButton = false
@State private var showingAlert1 = false
@State private var showingAlert2 = false
var body: some View {
Group {
if showingOtherButton {
Button("Show Alert 2") {
showingAlert2 = true
}
.alert(isPresented: $showingAlert2) {
print("Alert 2 should be shown")
return Alert(title: Text("Alert 2"), dismissButton: .default(Text("Ok")))
}
} else {
Button("Show other Button") {
self.showingOtherButton = true
}
Button("Show Alert 1") {
showingAlert1 = true
}
}
}
.alert(isPresented: $showingAlert1) {
Alert(title: Text("Alert 1"), dismissButton: .default(Text("OK")))
}
}
}
Placing the alert 1 modifier onto the "Show Alert 1" button directly makes it work, but I don't understand why.
Upvotes: 2
Views: 1458
Reputation: 606
Your second alert should go in the same place as the first - attached to the Group
view, not to the Button
:
Group {
if showingOtherButton {
Button("Show Alert 2") {
showingAlert2 = true
}
} else {
Button("Show other Button") {
self.showingOtherButton = true
}
Button("Show Alert 1") {
showingAlert1 = true
}
}
}
.alert(isPresented: $showingAlert1) {
Alert(title: Text("Alert 1"), dismissButton: .default(Text("OK")))
}
.alert(isPresented: $showingAlert2) {
print("Alert 2 should be shown")
return Alert(title: Text("Alert 2"), dismissButton: .default(Text("Ok")))
}
Upvotes: 2