Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swiftui

I am trying to create ViewModifiers to hold all my type styles in SwiftUI. When I try to add a .fontWeight modifier I get the following error: Value of type 'some View' has no member 'fontWeight'

Is this possible? Is there a better way to manage type styles in my SwiftUI project?

struct H1: ViewModifier {
    func body(content: Content) -> some View {
        content
            .foregroundColor(Color.black)
            .font(.system(size: 24))
            .fontWeight(.semibold)
    }
}
like image 246
Gavin Jensen Avatar asked Aug 31 '19 22:08

Gavin Jensen


2 Answers

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)
        }
} 
like image 64
turingtested Avatar answered Dec 01 '22 18:12

turingtested


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()
like image 45
LuLuGaGa Avatar answered Dec 01 '22 16:12

LuLuGaGa