Ensuring Consistent SwiftUI Text Fonts and Styles

In a larger app, it is desirable to keep your Text (aka your labels) consistent. You may have a preferred style for all of your titles for example, and maybe you want all your form section headers to look the same throughout your app too.

Instead of applying the same modifiers throughout your app using .font() and .fontWeight() each time, you can ensure consistency and reduce repeated code by storing all of your styles in a single place.

Creating Your Styles#

To get started, create an extension to Text. By doing this, we can create some view modifiers that will return our view in the specific style that we want. These view modifiers can be used throughout the app, and when you want to switch up your design in the future, it can all be done from one place.

In this example, we have five different styles. These all use the standard Text modifiers that exist already, but will ensure that we won’t accidentally forget to update one of our Text views in the future.

extension Text {
    func titleStyle() -> some View {
        self
            .font(.title)
            .fontWeight(.bold)
    }
    
    func captionStyle() -> some View {
        self
            .font(.caption)
            .foregroundColor(.secondary)
    }
    
    func formLabelStyle() -> some View {
        self
            .fontWeight(.medium)
    }
    
    func headerStyle() -> some View {
        self
            .font(.headline)
            .fontWeight(.semibold)
            .multilineTextAlignment(.leading)
    }
    
    func toolbarStyle() -> some View {
        self
            .fontWeight(.medium)
    }
}

Once created, these styles are really easy to use!

struct ContentView: View {
    var body: some View {
        VStack {
            Text("My Title Style").titleStyle()
            Text("My Caption Style").captionStyle()
            Text("My Form Label Style").formLabelStyle()
            Text("My Header Style").headerStyle()
            Text("My Toolbar Style").toolbarStyle()
        }
    }
}

Conclusion#

If this tutorial helped you in any way, I’d really appreciate a share on Twitter. You can reach out to me via Twitter if you have any questions, or to show me what you’ve been up to!