The commands scene modifier builds the app's menu system declaratively. On macOS the
commands become main-menu items; on iPadOS, commands with keyboard shortcuts appear in the
HUD shown when the user holds the Command key. iOS 14 and macOS 11 and up.
Adding a Menu
Attach .commands to a scene and compose menus in its CommandBuilder closure.
CommandMenu takes a title and a ViewBuilder; Button, Picker, Toggle, and Divider
all work as menu items.
@main
struct MyApp: App {
@State private var filter = 1
var body: some Scene {
WindowGroup { ContentView() }
.commands {
CommandMenu("First menu") {
Button("Print message") { print("Hello World!") }
.keyboardShortcut("p")
Divider()
Picker(selection: $filter, label: Text("Filter")) {
Text("Option 1").tag(1)
Text("Option 2").tag(2)
}
}
}
}
}
Reusable Command Types
Conform to the Commands protocol to package a menu for reuse, the same shape as a custom
View.
struct SortingCommands: Commands {
@Binding var sorting: Int
var body: some Commands {
CommandMenu("Sort") {
Picker(selection: $sorting, label: Text("Sorting")) {
Text("Option 1").tag(1)
Text("Option 2").tag(2)
}
}
}
}
// .commands { SortingCommands(sorting: $sorting) }
Extending System Menus
CommandGroup inserts items before or after a system menu location, or replaces it.
CommandGroupPlacement names the anchors: newItem, saveItem, printItem, undoRedo,
pasteboard, windowArrangement, help, appInfo, and more.
.commands {
CommandGroup(before: .newItem) {
Button("before item") { }
}
CommandGroup(replacing: .appInfo) {
Button("Custom app info") { }
}
}
SwiftUI also ships ready-made groups: add TextEditingCommands() and
TextFormattingCommands() to get the standard text menus without writing them.