Scene Commands, how to create a submenus???

The scene Commands are great way to create a main menu Like Project between the standard view || window menu on macOS,

Is there a way to construct submenus?

Currently the commands are listed in a main menu however is it possible to append a menu item that has its own submenu in SwiftUI?

Accepted Reply

You can create submenus using the Menu type (née MenuButton). This also works in other menu types, like context menus and pop-up buttons.

Code Block
@main
struct TestApp: App {
    var body: some Scene {
        WindowGroup {
            Text("Hello, SwiftUI!").padding()
        }
        .commands {
            CommandMenu("Example") {
                Button("Menu Item", action: ...)
                Divider()
                Menu("Submenu") {
                    Button("Menu Item", action: ...)
                }
            }
        }
    }
}


FYI, there are some known issues that prevent state changes from updating menu bar menus as expected, which more or less prevents sharing state between your main menu and your windows. This will be addressed in a future seed.

Replies

You can create submenus using the Menu type (née MenuButton). This also works in other menu types, like context menus and pop-up buttons.

Code Block
@main
struct TestApp: App {
    var body: some Scene {
        WindowGroup {
            Text("Hello, SwiftUI!").padding()
        }
        .commands {
            CommandMenu("Example") {
                Button("Menu Item", action: ...)
                Divider()
                Menu("Submenu") {
                    Button("Menu Item", action: ...)
                }
            }
        }
    }
}


FYI, there are some known issues that prevent state changes from updating menu bar menus as expected, which more or less prevents sharing state between your main menu and your windows. This will be addressed in a future seed.
Great, thank you !!!
Is there any way to add (or change) the state of the menu buttons to show a checkmark next to a menu item? (Basically the equivalent to NSMenuItem's state property in AppKit.)
To @wavid—probably best to create submit separate posts for follow-up questions, but: you can use a Toggle instead of Button if you want a menu item with a checkmark. And you can (in theory—might be buggy and broken right now) use NavigationLink to open a view in a new window on macOS.