The method of calling an alert in swiftUI is supposed to be simpler than ever, a simple example of this would be
struct ContentView: View {
@State private var showingAlert = false
var body: some View {
Button(action: {
self.showingAlert = true
}) {
Text("Show Alert")
}
.alert(isPresented: $showingAlert) {
Alert(title: Text("Important message"), message: Text("Wear sunscreen"), dismissButton: .default(Text("Got it!")))
}
}
}
However, even though I am calling an alert and can verify the method is being called, my alert does not display.
In my code I have the following Struct
private struct resetButton: View {
@State var isResetting = false
var body: some View {
Button("Reset"){
self.isResetting = true
}.alert(isPresented: $isResetting) {
print("We get here")
return
Alert(title: Text("Are you sure?"), message: Text("This will erase your Access Key."), primaryButton: .destructive(Text("Reset")) {
clearToken()
clearAccessKey()
clearUsername()
}, secondaryButton: .cancel(Text("Cancel")))
}
}
}
Which is called in the main view simply by resetButton()
.
However, when I push this button, despite isResetting
equalling true, the alert does not display. I have verified that my .alert
method is being called as the console prints
we get here
the first time the button is pushed.
However, the Alert is never displayed.
An alert is displayed correctly elsewhere in this same view with
.alert(isPresented: $failedLogin) {
self.password = ""
return
Alert(title: Text("Invalid Login"), message: Text("Please verify your credentials and try again"), dismissButton: .default(Text("Ok")))
}
When a @State
variable named failedLogin
is set true, however, the aforementioned alert is never presented.
My first impression is that this may be a bug in Swift, if it is I'll report it to apple. However, maybe something I'm doing isn't working because of an error on my part.
Edit:
As clarified in the answer below, the problem seems to be relating to the fact that my resetButton()
was trying to throw up an alert in a view that already contains an alert. Apparently you can't have multiple alerts in one view.