Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Add a Button to a NavigationBar in SwiftUI
Written by Team Kodeco

Adding buttons to the navigation bar provides quick access to app features while preserving screen real estate. SwiftUI allows us to accomplish this conveniently using the toolbar modifier.

With SwiftUI’s toolbar modifier, you can position a button on either side of the navigation bar.

Note: The navigationBarItems modifier is deprecated. Use toolbar instead for new code.

Here’s an example of how to add a button to the navigation bar using toolbar:

struct ContentView: View {
  var body: some View {
    NavigationStack {
      Text("Hello, world!")
        .toolbar {
          ToolbarItem(placement: .navigationBarTrailing) {
            Button(action: {
              // Code for button action goes here
            }) {
              Image(systemName: "gear")
            }
          }
        }
    }
  }
}

Here’s what your preview should look like:

A view that adds a button to the navigation bar in SwiftUI.
A view that adds a button to the navigation bar in SwiftUI.

In this example, we add a button to the trailing edge of the navigation bar by specifying the placement as .navigationBarTrailing. The button action is defined in the action closure of the Button view. The button is represented by an image of a gear.

You can add multiple buttons to the navigation bar by including multiple ToolbarItems within the toolbar modifier. These buttons can be placed on either side or even both sides of the navigation bar, providing a flexible approach to designing your user interface.

In summary, by using the toolbar modifier to add buttons to the navigation bar, you can create a clean, minimal user interface that still offers essential features to your users.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.