I want to do something similar to the code below, where it shows an alert when a user taps a navigation bar item button. However the code below doesn't work, the alerts do not display.
I can't add the alert modifiers to the NavigationView
because my actual app is more complex and the VStack
is a view in another file, also adding multiple alert modifiers to the same view doesn't work (only the last one added works).
import SwiftUI
struct SOQuestionView: View {
@State private var showAlert1 = false
@State private var showAlert2 = false
var body: some View {
NavigationView {
VStack {
Text("Click button in toolbar")
}
.navigationBarTitle(Text("Title"))
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button(action: {
showAlert1 = true
}) {
Image(systemName: "square.and.arrow.up")
}
.alert(isPresented: $showAlert1) {
Alert(title: Text("Alert 1"))
}
}
ToolbarItem(placement: .navigationBarTrailing) {
Button(action: {
showAlert2 = true
}) {
Image(systemName: "square.and.arrow.up.fill")
}
.alert(isPresented: $showAlert2) {
Alert(title: Text("Alert 2"))
}
}
}
}
}
}