SwiftUI Blog

Mastering SwiftUI: Your Guide to Building Beautiful, Intuitive Apps.

Navigation Title and Toolbar


We can configure the navigation bar by adding the title and defining how to display it.

struct ContentView: View {
    var body: some View {
        NavigationStack {
            TabView {
                Tab("Contacts", systemImage: "rectangle.stack.person.crop.fill") {
                    Text("First tab")
                }
                Tab("Chat", systemImage: "message.fill") {
                    Text("Second tab")
                }
            }.navigationTitle("Vehicle")
        }
    }
}

To achieve this:

It is also possible to set the title at the top and center it by adding the display mode like this:

struct ContentView: View {
    var body: some View {
        NavigationStack {
            TabView {
                Tab("Contacts", systemImage: "rectangle.stack.person.crop.fill") {
                    Text("First tab")
                }
                Tab("Chat", systemImage: "message.fill") {
                    Text("Second tab")
                }
            }.navigationTitle("Vehicle")
            .navigationBarTitleDisplayMode(.inline)
        }
    }
}
    

The default display mode is automatic, which means the title is displayed large and aligned to the left. However, if there is a list on the screen, the title moves to the center in inline mode when the screen is scrolled.

Toolbar

Another important component is the toolbar, where we can add buttons, navigation links, and other elements, as shown on this screen.

On the left, we have a NavigationLink (the plus), and on the right, a button (add). Let’s see how to create them:

struct ContentView: View {
    var body: some View {
        NavigationStack {
            TabView {
                Tab("Contacts", systemImage: "rectangle.stack.person.crop.fill") {
                    Text("First tab")
                }
                Tab("Chat", systemImage: "message.fill") {
                    Text("Second tab")
                }
            }.navigationTitle("Vehicle")
            .navigationBarTitleDisplayMode(.automatic)
            .toolbar {
                ToolbarItem(placement: .topBarTrailing) {
                    Button("Add") {
                        print("Add")
                    }
                }
                ToolbarItem(placement: .topBarLeading) {
                    NavigationLink(destination: EmptyView()) {
                        Image(systemName: "plus")
                    }
                }
            }
        }
    }
}

Step by step, we are learning all the components needed to create an impressive app.