I'm trying to create some default fonts for my app using modifiers. If there's an easier way, I'd love to know. Currently, I have
struct PrimaryLabel: ViewModifier {
func body(content: Content) -> some View {
content
.font(Font.body.smallCaps())
.font(.system(size: 20, weight: .light, design: .serif)) // this is not working. Only the first one will '.font' will work
}
}
usability:
Text("Hello World").modifier(PrimaryLabel())
Is there a way to change the font type (ie like using AmericanTypewriter-Light font), make it all capitalized, and use a style like weight: .light, design: .serif
, bold etc? I don't want to define every single Text. The second .font
modifier in the struct is not working.
first modifier is only visible, which is logical, try to apply few ,background or .foregroundColor .... it works the same way.
try
VStack {
Text("ALFA").font(.largeTitle)
Text("Beta").foregroundColor(Color.red)
}
.font(.system(size: 150))
.foregroundColor(Color.blue)
You can create Font with different initializers
init(CTFont)
Gets a font from a platform font instance.
static func system(Font.TextStyle, design: Font.Design) -> Font
Gets a system font with the given style and design.
static func system(size: CGFloat, weight: Font.Weight, design: Font.Design) -> Font
Specifies a system font to use, along with the style, weight, and any design parameters you want applied to the text.
static func custom(String, size: CGFloat) -> Font
Gets a custom font with the given name and size.
And you can further style your Text
Styling a Text View
func bold() -> Text
Applies a bold font weight to the text.
func italic() -> Text
Applies italics to the text.
func fontWeight(Font.Weight?) -> Text
Sets the font weight of the text.
func baselineOffset(CGFloat) -> Text
Sets the baseline offset for the text.
func tracking(CGFloat) -> Text
Sets the tracking for the text.
func kerning(CGFloat) -> Text
Sets the spacing, or kerning, between two characters.
func underline(Bool, color: Color?) -> Text
Applies an underline to the text.
func strikethrough(Bool, color: Color?) -> Text
Applies a strikethrough to the text.
WARNING!! Not every combination is supported! see How to apply .italic() to .largeTitle Font?
extension View {
func primaryLabelStyle(_ weight: Font.Weight) -> some View {
return self.modifier(PrimaryLabel(weight: weight))
}
}
struct PrimaryLabel: ViewModifier {
let weight: Font.Weight
func body(content: Content) -> some View {
content
.font(Font.body.smallCaps())
.font(.system(size: 20, weight: weight, design: .serif)) // this is not working. Only the first one will '.font' will work
}
}
Text("Hello World").primaryLabelStyle(.light)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.