Windows and commands
Add menu commands and shortcuts
Expose important actions through normal macOS menus and give frequent actions discoverable keyboard shortcuts.
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 next to each item.
None of this exists on iOS. The menu bar is the most Mac-specific thing you’ll build.
Add a command to the File menu
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, shown next to the label.
Add your own menu
When your actions deserve a top-level menu of their own, use CommandMenu:
CommandMenu("Notes") {
Button("Sort by Title") { model.sortByTitle() }
Divider()
Button("Delete All Notes", role: .destructive) {
model.deleteAll()
}
.disabled(model.notes.isEmpty)
}
Commands declared at the scene level work no matter which view has focus. That’s the point. Put them on the scene, not buried inside a view, and they stay available while the user moves between windows.
Disable what makes no sense
Notice the .disabled(model.notes.isEmpty) line. It keeps “Delete All Notes” grayed out when there’s nothing to delete.
A grayed-out item communicates state. An item that clicks and silently does nothing communicates that your app is buggy.
Verify it
Run the app. The File menu should show New Note with ⇧⌘N beside it. Press the shortcut and 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.
Don’t steal system shortcuts
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. My advice: keep the plain ⌘-letter combinations for the most standard actions, and use ⇧⌘ or ⌥⌘ for the ones specific to your app.
Lesson completed