How it works
ToolbarCommands is a built-in command group that adds the standard toolbar menu items — commands like Show Toolbar and Customize Toolbar — to your app's menu bar. It conforms to the Commands protocol, so you supply it inside a scene's commands modifier rather than building those menu entries by hand. Reach for it when a window presents a toolbar and you want users to control that toolbar from the menu bar with the system-standard wording and key equivalents, instead of writing your own menu commands. Because the items are system-provided, they stay automatically in sync with the toolbar a window actually shows.
Give a window a toolbar with the
toolbarmodifierToolbarCommandsoperates on whatever toolbar your window content defines, so the toolbar comes first. In the example, theTextview insideNavigationStackattaches a.toolbar { ... }containing aToolbarItemGroup(placement: .primaryAction)withbold,italic, andunderlineButtons — that group is the toolbar the menu commands will reference.Add
ToolbarCommandsto a scene's command setInstantiate it with
ToolbarCommands()and pass it to thecommandsmodifier on aWindowGroup(or other scene). Doing so installs the View menu's toolbar entries; nothing in the toolbar declaration changes, and you write noButtonorCommandMenuof your own for these items.Let the system populate the standard menu items
Once added,
ToolbarCommandscontributes platform-standard entries such as Show/Hide Toolbar and Customize Toolbar, complete with their conventional titles and key equivalents. These act on the focused window's toolbar — the one holding the.primaryActiongroup with thebold/italic/underlinebuttons — without any manual wiring.Compose it with other command groups
As a
Commandsvalue,ToolbarCommandscan sit alongside other groups (for example viaSidebarCommandsor your ownCommandGroup) within a singlecommandsmodifier. SwiftUI merges them into the menu bar, placing the toolbar items in their expected location relative to the rest.
NavigationStack window in a WindowGroup { ... }.commands { ToolbarCommands() }, run on macOS, and watch the View menu gain Show Toolbar and Customize Toolbar items that drive the same toolbar holding the bold/italic/underline buttons.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 ToolbarCommandsDemo: View {
@State private var bold = false
var body: some View {
NavigationStack {
Text(bold ? "Bold On" : "Bold Off")
.font(.title2)
.fontWeight(bold ? .bold : .regular)
.padding()
.navigationTitle("Editor")
.toolbar {
ToolbarItemGroup(placement: .primaryAction) {
Button(action: { bold.toggle() }) {
Image(systemName: "bold")
}
Button(action: {}) {
Image(systemName: "italic")
}
Button(action: {}) {
Image(systemName: "underline")
}
}
}
}
}
}