I want to have two unique alerts attached to the same Button
view. When I use the code below, only the alert on the bottom works.
I\'m using the officia
There's a variation on this solution which only uses one state variable rather than two. It uses the fact that there is another .alert()
form which takes an Identifiable
item rather than a Bool, so extra information can be passed in that:
struct AlertIdentifier: Identifiable {
enum Choice {
case first, second
}
var id: Choice
}
struct ContentView: View {
@State private var alertIdentifier: AlertIdentifier?
var body: some View {
HStack {
Button("Show First Alert") {
self.alertIdentifier = AlertIdentifier(id: .first)
}
Button("Show Second Alert") {
self.alertIdentifier = AlertIdentifier(id: .second)
}
}
.alert(item: $alertIdentifier) { alert in
switch alert.id {
case .first:
return Alert(title: Text("First Alert"),
message: Text("This is the first alert"))
case .second:
return Alert(title: Text("Second Alert"),
message: Text("This is the second alert"))
}
}
}
}