How it works
CommandMenu declares a new, top-level menu in your app's main menu bar, sitting alongside the system-provided menus like File, Edit, and View. You add it to the commands modifier of a Scene so its title and contents become part of the menu bar that's always available while your app is frontmost, rather than living inside a particular window. Reach for CommandMenu when a group of commands is global to the app and deserves its own named menu — and pair the commands inside it with keyboard shortcuts so users can drive your app without the mouse.
Give the menu a title with CommandMenu(_:)
CommandMenuis initialized with a localized title string and a content closure; the title is the label that appears in the menu bar. In the example, the menu's items live in aMenu("File")content closure, the same trailing-closure patternCommandMenuuses to declare its own entries.Populate it with menu-item views
Inside the closure you compose ordinary command views —
Buttons for actions andDividers to group them. HereButton("New"),Button("Open"), andButton("Save")each carry an action that updateslastAction, whileDivider()visually separates the saving command from the others;CommandMenuarranges these as the rows of its menu.Attach actions and run them from anywhere
Each
Button's action closure is the work the command performs when chosen. Because aCommandMenubelongs to the app rather than a single view, these closures typically mutate app- or scene-level state; in the example the buttons assign"New","Open", and"Save"to the@StatepropertylastAction, which theText(lastAction)view then displays.Install it through the commands modifier
A
CommandMenuonly takes effect when returned from acommands { }builder on aScenesuch asWindowGroup. That placement is what promotes the menu out of the window content shown here — theVStackwith itsTextandMenu— and into the system menu bar where it stays reachable across windows.
Button("Save"), with .keyboardShortcut("s") so choosing it from the menu — or pressing Command-S — fires the same action and updates lastAction.Example & preview
Press Run live & edit to compile it in your browser — then edit the Swift on the left and the preview re-renders live.
struct CommandMenuDemo: View {
@State private var lastAction = "No action yet"
var body: some View {
VStack(spacing: 12) {
Text("CommandMenu adds a top-level menu")
.font(.headline)
Text(lastAction)
.foregroundStyle(.secondary)
Menu("File") {
Button("New") { lastAction = "New" }
Button("Open") { lastAction = "Open" }
Divider()
Button("Save") { lastAction = "Save" }
}
}
.padding()
}
}