How to create a custom reusable toolbar in SwiftUI
Learn how to abstract a SwiftUI toolbar into a component.
03 Jul 2023 · 2 min read
When creating a toolbar in SwiftUI, we may need to reuse it in multiple screens. To avoid code duplication, we can use SwiftUI's ToolbarContent type to abstract the toolbar into its own component.
Let's look at how to do that.

The following example creates a navigation bar with a custom back button and a title:
struct SomeCustomToolBarContent: ToolbarContent {let title: String@Environment(\.presentationMode) var presentationModevar body: some ToolbarContent {ToolbarItemGroup(placement: .navigationBarLeading) {Button(action: {presentationMode.wrappedValue.dismiss()}) {Image("someCustomBackButtonImage")}}ToolbarItem(placement: .principal) {Text(title).font(titleFont).foregroundColor(titleColor)}}}
To use it, we can use SwiftUI's toolbar modifier as follows:
someView.toolbar {SomeCustomToolBarContent(title: "SomeTitle")}.navigationBarBackButtonHidden(true).navigationBarShadow()
We can go a step further to add even more abstraction by creating a custom view modifier:
struct SomeCustomToolBarModifier: ViewModifier {let title: Stringfunc body(content: Content) -> some View {return content.toolbar {SomeCustomToolBarContent(title: title)}.navigationBarBackButtonHidden(true).navigationBarShadow()}}
With that in place, we can now apply the toolbar as follows:
someView.modifier(SomeCustomToolBarModifier(title: "SomeTitle"))
To make the call above even shorter, we could additionally create a View extension:
extension View {func someCustomToolbar(title: String) -> some View {return self.modifier(SomeCustomToolBarModifier(title: title))}}
Now, we are able to apply the toolbar with the following call:
someView.someCustomToolbar(title: "SomeTitle")

Newsletter
Like to support my work?
Say hi
Related tags
Articles with related topics
Latest articles and tips