Logo for tanaschita.com

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.

Sponsorship logo
Capture HTTP(s) traffic with Proxyman
Proxyman - Your ultimate man-in-the-middle proxy to effortlessly capture, inspect, and manipulate HTTP(s) traffic on macOS, Windows, iOS, and Android devices.
Get started for free

The following example creates a navigation bar with a custom back button and a title:

struct SomeCustomToolBarContent: ToolbarContent {
let title: String
@Environment(\.presentationMode) var presentationMode
var 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: String
func 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")
Sponsorship logo
Capture HTTP(s) traffic with Proxyman
Proxyman - Your ultimate man-in-the-middle proxy to effortlessly capture, inspect, and manipulate HTTP(s) traffic on macOS, Windows, iOS, and Android devices.
Get started for free

Newsletter

Image of a reading marmot
Subscribe

Like to support my work?

Say hi

Related tags

Articles with related topics

swiftui

swift

ios

How to present a local html file in SwiftUI

Learn how to use WKWebView with SwiftUI.

11 Sep 2023 · 3 min read

Latest articles and tips

© 2023 tanaschita.com

Privacy policy

Impressum