Windows and commands
Add menu commands and shortcuts
Expose important actions through normal macOS menus and give frequent actions discoverable keyboard shortcuts.
12 minute lesson
A Mac app without menu bar items feels broken. Users look for actions in the menus, search for them with the Help menu, and learn shortcuts from the labels shown next to each item. On iOS none of this exists — the menu bar is the most Mac-specific surface you will build.
SwiftUI attaches menus to scenes with the .commands modifier. Add it to the WindowGroup:
WindowGroup {
ContentView()
.environmentObject(model)
}
.commands {
CommandGroup(after: .newItem) {
Button("New Note") {
model.createNote()
}
.keyboardShortcut("n", modifiers: [.command, .shift])
}
}
CommandGroup(after: .newItem) inserts your button into the File menu, right after the standard New item. SwiftUI turns the Button into a real menu item and the keyboardShortcut into ⇧⌘N, displayed beside the label.
When your actions deserve their own top-level menu, use CommandMenu:
CommandMenu("Notes") {
Button("Sort by Title") { model.sortByTitle() }
Divider()
Button("Delete All Notes", role: .destructive) {
model.deleteAll()
}
.disabled(model.notes.isEmpty)
}
Commands placed at the scene level work no matter which view has focus. That is the point: put them on the scene, not buried inside a view, and they stay available while the user moves between windows.
Disable commands that make no sense right now. The .disabled(model.notes.isEmpty) line keeps “Delete All Notes” grayed out when there is nothing to delete. A grayed-out item communicates state. An item that clicks and silently does nothing communicates that your app is buggy.
Run the app and verify. The File menu should show New Note with ⇧⌘N beside it. Press the shortcut — a note appears. Then open the Help menu and type “new” into the search field: macOS finds your command and points a floating arrow at it. You wrote none of that.
The classic mistake is claiming a shortcut the system already uses. ⌘N, for example, already means New Window for a WindowGroup scene. Assign it to New Note and you silently take a standard feature away from your users. Check the existing menus before choosing a shortcut, and keep the plain ⌘-letter combinations for the most standard actions.
Lesson completed