简体   繁体   中英

How to display Alert dialog on MacOS using SwiftUI

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM