How to add button to navigation bar in SwiftUI

In this tutorial we’re going to learn how to add buttons and images to navigation bar in SwiftUI’s NavigationView. In order to achieve this goal we’re going to use the navigationBarItems modifier which lets you specify leading and/or trailing bar items (e.g., buttons, images or other SwiftUI views). Leading items are being added to the left side of the screen edge and trailing items are being added to the right side of the screen edge.

In order to add one trailing Edit button to the navigation bar use the following code:

struct ContentView: View {
    var body: some View {
        NavigationView {
            Text("List of SwiftUI tutorials")

            .navigationBarTitle("Tutorials")
            .navigationBarItems(trailing:
                Button(action: {
                    print("Edit button pressed...")
                }) {
                    Text("Edit")
                }
            )
        }
    }
}
Trailing Edit button in the navigation bar using navigationBarItems
Trailing Edit button in the navigation bar using navigationBarItems

Add one leading Edit button to the navigation bar:

.navigationBarItems(leading:
    Button(action: {
        print("Edit button pressed...")
    }) {
        Text("Edit")
    }
)

Add trailing image button to the navigation bar using an SF Symbol:

.navigationBarItems(trailing:
    Button(action: {
        print("User icon pressed...")
    }) {
        Image(systemName: "person.crop.circle").imageScale(.large)
    }
)
Trailing image button in the navigation bar using navigationBarItems
Trailing image button in the navigation bar using navigationBarItems

Add multiple trailing buttons to the navigation bar using HStack:

.navigationBarItems(trailing:
    HStack {
        Button(action: {
            print("Reload button pressed...")
        }) {
            Text("Reload")
        }
        
        Button(action: {
            print("Edit button pressed...")
        }) {
            Text("Edit")
        }
    }
)

Related tutorials:

Questions, comments or suggestions? Follow us on Twitter @theswiftguide