How it works
Commands is the protocol you adopt to describe a scene's menu bar and keyboard command structure declaratively, the same way View describes an interface. Conforming types expose a body of type some Commands, built from command primitives like CommandMenu, CommandGroup, and CommandGroupPlacement, so menu items and their shortcuts live in their own composable, testable unit rather than being wired up imperatively. Reach for Commands when an app needs to add, replace, or remove top-level menu commands and global keyboard shortcuts, and attach that definition to a scene with the commands(content:) modifier.
Conform a type to Commands and provide a body
Adopting
Commandsis parallel to adoptingView: you implement abodycomputed property whose result type issome Commands. HereDemoCommandsconforms toCommandsand itsvar body: some Commandsreturns the command content, giving you a single value that represents an entire block of menu commands.Add a top-level menu with CommandMenu
CommandMenuis a command primitive that inserts a brand-new menu into the menu bar, after the app's standard menus. Its label becomes the menu title and its trailing closure holds the menu's items. In the exampleCommandMenu("Actions")creates an Actions menu whose body contains the individual command buttons.Express each command as a Button inside the menu
Commands are ordinary
Buttonvalues; SwiftUI renders them as menu items and runs their action when chosen. TheRefreshandClearbuttons supply both the visible menu titles and the closures that fire when the user selects them.Bind a keyboard shortcut with keyboardShortcut
The
keyboardShortcut(_:)modifier attaches a global key equivalent to a command so it can be invoked without opening the menu. Applying.keyboardShortcut("r")and.keyboardShortcut("k")binds Command-R to Refresh and Command-K to Clear, mirroring the \u2318R and \u2318K hints shown alongside the menu.
Button("Reset") {} with .keyboardShortcut("l") inside the CommandMenu("Actions") block to watch a new item and its Command-L shortcut join the same menu.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 CommandsDemo: View {
struct DemoCommands: Commands {
var body: some Commands {
CommandMenu("Actions") {
Button("Refresh") {}
.keyboardShortcut("r")
Button("Clear") {}
.keyboardShortcut("k")
}
}
}
var body: some View {
VStack(alignment: .leading, spacing: 8) {
Text("Custom Menu Commands")
.font(.headline)
Label("Actions \u{203A} Refresh \u{2318}R", systemImage: "arrow.clockwise")
Label("Actions \u{203A} Clear \u{2318}K", systemImage: "trash")
}
.padding()
}
}