如何使用 SwiftUI 在 MacOS 上显示警报对话框

How to display Alert dialog on MacOS using SwiftUI

如何使用 SwiftUI 从 MacOS 应用程序的菜单项中显示警告对话框? 适用于 iOS @State var isOn = false.alert("title", isPresented: isOn) {..} 的常用代码不起作用。

@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")
            }
        }
    }
}

通常的代码工作正常。您永远不会尝试将 Alert 塞进 Button。你不会在这里做的。

@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")
                }
            }
        }
    }
}