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)
}
}
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)
}
}
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With