How to add .fontWeight as part of a ViewModifer in SwiftUI

You can achieve this by declaring the function in an extension on Text, like this:

extension Text {

    func h1() -> Text {
        self
            .foregroundColor(Color.black)
            .font(.system(size: 24))
            .fontWeight(.semibold)
    }
}

To use it simply call:

Text("Whatever").h1()

Font has weight as one of it's properties, so instead of applying fontWeight to the text you can apply the weight to the font and then add the font to the text, like this:

struct H1: ViewModifier {
    // system font, size 24 and semibold
    let font = Font.system(size: 24).weight(.semibold)

    func body(content: Content) -> some View {
        content
            .foregroundColor(Color.black)
            .font(font)
        }
} 

Tags:

Swiftui