swiftuiswiftui-text

How to shorten long reusable modifiers like font style, foreground styles, etc


I have a custom font modifier that I am using often, however it makes the code very long as I need to add it in multiple places.

This is the modifier:

.font(.custom("Bebas Neue", size: 24)).foregroundStyle(LinearGradient(gradient: Gradient(colors: [Color("lb"), Color("rb")]),startPoint: .top, endPoint: .bottom))

How can I shorten this so I can import it ideally with a single word or so?


Solution

  • You can use a custom view modifier.

    Custom Modifier

    struct TextModifier: ViewModifier {
        
        let gradient = LinearGradient(gradient: Gradient(colors: [Color("lb"), Color("rb")]),startPoint: .top, endPoint: .bottom)
        
        func body(content: Content) -> some View {
            content
                .font(.custom("Bebas Neue", size: 24)).foregroundStyle(gradient)
        }
    }
    

    Usage

    Text("How are you today? ☀️")
        .modifier(TextModifier())
    

    Extra (optional)

    If you want an easier way to use the modifer you can create an extension on View, like so:

    extension View {
        func textStyle() -> some View {
            modifier(TextModifier())
        }
    }
    

    Then to use it:

    Text("How are you today? ☀️")
        .textStyle()
    

    More about ViewModifiers and Extensions

    Hope this helps :)