5

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

1 Answer 1

11

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")
                }
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.