SwiftUI Quick Tip - Custom Navigation Bar Title

SwiftUI Quick Tip - Custom Navigation Bar Title
Photo by Barn Images / Unsplash

You can set the navigation bar title in SwiftUI with the following view modifier,

.navigationBarTitle("My Title")

But what if you don't want the Title to be a String or a LocalizedStringKey? That is where the .toolbar view modifier and the principal ToolbarItemPlacement object come in to play. For any view inside of a NavigationView you can add the following view modifier to get any view you would like as the navigation "title."

.toolbar {
   ToolbarItemGroup(placement: .principal) {
      // Your custom view here
   }
}

This is a great way to add you app's logo to the navigation bar. The principal placement in iOS will be positioned centered in the navigation bar. But keep in mind that placement will have different meanings for different platforms (iOS, macOS, watchOS, etc..).