Custom navigation bar title view in SwiftUI

⋅ 1 min read ⋅ SwiftUI WWDC20

Table of Contents

In iOS 14, SwiftUI has a way to customize a navigation bar title view with a new toolbar modifier. This is the same thing as setting navigationItem.titleView in UIKit.

To customize a navigation bar title view in SwiftUI, we simply set ToolbarItem of placement type .principal to a new toolbar modifier.

NavigationView { // <1>
Text("Hello, SwiftUI!")
.navigationBarTitleDisplayMode(.inline)
.toolbar { // <2>
ToolbarItem(placement: .principal) { // <3>
VStack {
Text("Title").font(.headline)
Text("Subtitle").font(.subheadline)
}
}
}
}

<1> Because this is a customize of navigation bar title, a view needs to be embedded inside a NavigationView.
<2> Set .toolbar modifier to a root view of NavigationView.
<3> Set ToolbarItem of placement type .principal with content that you want to show as a title view.

The above code would produce this in SwiftUI.

Custom title view in SwiftUI
Custom title view in SwiftUI

This isn't restricted to just text; you can use an image or button in the title view.

The following example uses SF Symbols in a title view.

NavigationView {
Text("Hello, SwiftUI!")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .principal) {
HStack {
Image(systemName: "sun.min.fill")
Text("Title").font(.headline)
}
}
}
}
Custom title view with SF Symbols
Custom title view with SF Symbols

The following example uses a button in a title view.

NavigationView {
Text("Hello, SwiftUI!")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .principal) {
VStack {
Text("Title").font(.headline)
Button("Subtitle") {

}
}
}
}
}
Custom title view with a button
Custom title view with a button

You can easily support sarunw.com by checking out this sponsor.

Sponsor sarunw.com and reach thousands of iOS developers.

Read more article about SwiftUI, WWDC20, or see all available topic

Enjoy the read?

If you enjoy this article, you can subscribe to the weekly newsletter.
Every Friday, you'll get a quick recap of all articles and tips posted on this site. No strings attached. Unsubscribe anytime.

Feel free to follow me on Twitter and ask your questions related to this post. Thanks for reading and see you next time.

If you enjoy my writing, please check out my Patreon https://www.patreon.com/sarunw and become my supporter. Sharing the article is also greatly appreciated.

Become a patron Buy me a coffee Tweet Share
Previous
A first look at matchedGeometryEffect

This modifier can interpolate position and size between two views. This is one of the most exciting features for me. Let's see what is capable of in this beta.

Next
UIToolbar in SwiftUI

In iOS 14, we finally have a way to set a toolbar for a view in a navigation view.

← Home