How it works
SidebarCommands is a built-in Commands type that adds the standard system menu items for showing, hiding, and toggling a sidebar to your app's menu bar. Apps built around a NavigationSplitView get a leading sidebar column automatically, but users also expect to control its visibility from the View menu and with the matching keyboard shortcut; SidebarCommands supplies exactly those commands so you don't have to author them by hand. Reach for it in the commands builder of a Scene whenever your app presents a sidebar and you want the platform's familiar "Toggle Sidebar" behavior to appear and work consistently.
Present a sidebar with
NavigationSplitViewSidebarCommandsoperates on the sidebar that a multi-column navigation container creates. Here the sidebar is the leading column ofNavigationSplitView— aList(selection: $selection)of mailbox rows titled"Mailboxes"— paired with adetailcolumn. This column is the surface whose visibility the commands will manage.Add the commands in a scene's
commandsbuilderSidebarCommandsconforms to theCommandsprotocol, so you place it inside the.commands { }modifier on aScene(typically theWindowGrouphostingSidebarCommandsDemo). Instantiating it withSidebarCommands()registers its menu items with the app; it carries no parameters because the items it provides are fixed by the platform.Get the standard View-menu items for free
Once registered,
SidebarCommandsinjects the system's sidebar entries — including "Toggle Sidebar" — into the View menu, complete with their conventional keyboard shortcut. These commands target the sidebar column produced byNavigationSplitView, so choosing them collapses or reveals theListof"Inbox","Sent", and"Drafts"without any additional wiring.Compose it alongside other
CommandsBecause it is an ordinary
Commandsvalue,SidebarCommandscan sit next to other groups in the samecommandsbuilder — such asTextEditingCommandsor your ownCommandMenu— and SwiftUI merges them all into the menu bar. This lets you opt into the standard sidebar items while keeping full control over the rest of your app's menus.
SidebarCommandsDemo in a WindowGroup and attach .commands { SidebarCommands() }, then run the app and watch the "Toggle Sidebar" item appear in the View menu and collapse the List of mailboxes when invoked.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 SidebarCommandsDemo: View {
@State private var selection: String? = "Inbox"
var body: some View {
NavigationSplitView {
List(selection: $selection) {
Text("Inbox").tag("Inbox")
Text("Sent").tag("Sent")
Text("Drafts").tag("Drafts")
}
.navigationTitle("Mailboxes")
} detail: {
Text(selection ?? "Select a mailbox")
.font(.title2)
.padding()
}
}
}