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. Usetoolbar
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:
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 ToolbarItem
s 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.