Make a SwiftUI Toolbar Customizable

By customizable I mean letting the people using your app add, remove, and move toolbar items. Making a customizable toolbar in a SwiftUI app requires you to do the following:

The following code creates toolbar items in a customizable toolbar to push and pull version control changes to a remote repository:

.toolbar(id: "mainToolbar") {
  ToolbarItem(id: "push") {
    Button(
      action: {
        // Push the changes
      },
      label: {
        Label("Push", systemImage: "square.and.arrow.up")
      }
    ).accessibilityLabel("Push Changes")
}

  ToolbarItem(id: "pull") {
    Button(
      action: {
        // Pull the changes
      },
      label: {
        Label("Pull", systemImage: "square.and.arrow.down")
      }
    ).accessibilityLabel("Pull Changes")
  }
}

Creating toolbar items outside the .toolbar modifier

If your toolbar has many items, moving the toolbar item creation code out of the .toolbar modifier makes the toolbar code cleaner. If your toolbar creation code is outside the .toolbar modifier, the variable or function must conform to the CustomizableToolbarContent protocol for the toolbar to be customizable.

The following code places the toolbar item creation code in its own variable:

@ToolbarContentBuilder
  private var toolbarContent: some CustomizableToolbarContent {
    ToolbarItem(id: "push") {
      Button(
        action: {
          // Push the changes
        },
        label: {
          Label("Push", systemImage: "square.and.arrow.up")
        }
      ).accessibilityLabel("Push Changes")
    }

  ToolbarItem(id: "pull") {
    Button(
      action: {
        // Pull the changes
      },
      label: {
        Label("Pull", systemImage: "square.and.arrow.down")
      }
    ).accessibilityLabel("Pull Changes")
  }

}

.toolbar(id: "mainToolbar") {
  toolbarContent
} 

Toolbar item groups

SwiftUI includes a ToolbarItemGroup struct that lets you create a group of toolbar items without wrapping each item in a ToolbarItem block. Unfortunately ToolbarItemGroup does not conform to CustomizableToolbarContent so you can’t use ToolbarItemGroup in a customizable toolbar. You must create the toolbar items using ToolbarItem.

You can add menu items to the View menu to hide/show the toolbar and customize the toolbar by adding the ToolbarCommands struct to the .commands modifier in the App struct.

.commands {
  ToolbarCommands()
}

Get the Swift Dev Journal Newsletter

Subscribe and get exclusive articles, a free guide on moving from tutorials to making your first app, notices of sales on books, and anything I decide to add in the future.

    We won't send you spam. Unsubscribe at any time.