How can I display an alert dialog box from a menu item for MacOS apps using SwiftUI
?
The usual code which works for iOS @State var isOn = false
and .alert("title", isPresented: isOn) {..}
doesn't work.
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}.commands {
CommandMenu("Test menu") {
Button(action: {
// I want to show an alert dialog dialog here.
}) {
Text("Click Me")
}
}
}
}
CodePudding user response:
The usual code works fine. You would never try to stuff an Alert
inside of a Button
. You wouldn't do it here.
@main
struct MyApp: App {
@State var isOn = false
var body: some Scene {
WindowGroup {
NavigationView {
ContentView()
.alert("title", isPresented: $isOn) {
Button("OK", role: .cancel) { }
}
}
}.commands {
CommandMenu("Test menu") {
Button(action: {
isOn = true
}) {
Text("Click Me")
}
}
}
}
}