Custom navigation bar title view in SwiftUI

SwiftUI WWDC20

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

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 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 — entirely for free.

← Home