Creating a SwiftUI Toolbar Button with an Image and a Label
Many toolbar buttons in Mac and iOS apps include an image and a label. The Mac apps Finder, Mail, and Pages are examples of apps whose toolbar buttons have an image and a label.
If you try to create a button in a SwiftUI toolbar with an image and a label, you will notice the label does not appear. You must do the following to create a toolbar button with an image and a label:
- Create a label style for the button.
- Add a
.labelStyle
modifier to your button label and use the label style you created.
Creating a Label Style
To create a label style, you must create a struct that conforms to the LabelStyle
protocol. Add a makeBody
function to the struct that returns a SwiftUI view.
A label style for a toolbar button should create a VStack with the image first and the text label second. Supply a font to use for the image and the label in the VStack.
struct VerticalLabelStyle: LabelStyle {
func makeBody(configuration: Configuration) -> some View {
VStack {
configuration.icon.font(.headline)
configuration.title.font(.footnote)
}
}
}
Add the .labelStyle Modifier
After creating the label style for your toolbar button, add a .labelStyle
modifier to the button’s label and supply the name of the struct you created for the label style. The following code shows an example of a SwiftUI button that uses a custom label style:
Button(action: {
isPublishing = true
}, label: {
Label("Publish", systemImage: "book.closed.fill")
.labelStyle(VerticalLabelStyle())
}).accessibilityLabel("Publish Book")
Credits
The answer from Eduardo to the following Stack Overflow question helped me with the code for this article: