0

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?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Pro Girl
  • 762
  • 7
  • 21

1 Answers1

4

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 :)

Ori
  • 567
  • 3
  • 9