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

Tam*_*mas 4 macos swift swiftui

如何使用 MacOS 应用程序从菜单项显示警报对话框SwiftUI?通常的代码适用于 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")
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Yrb*_*Yrb 9

通常的代码可以正常工作。你永远不会尝试将其填充AlertButton. 你不会在这里这样做。

@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")
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)