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")
}
)
}
}
}
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)
}
)
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:
- How to present a sheet modally in SwiftUI
- How to add text overlay on image in SwiftUI
- How to present new sheet view from navigationBarItems button in SwiftUI
Questions, comments or suggestions? Follow us on Twitter @theswiftguide