I'm trying to change the default font in SwiftUI for every view in my app.
What I want to avoid is to set it every time like so:
.font(.custom("FONT_NAME", size: 20))
What I want is to change it just one time for all Text views, and most important, I would like to keep using the modifiers:
.font(.caption)
without resetting the Text view to the system font.
But still I didn't find any solution, does anyone have one?
Hold the command key and click the text to bring up a pop-over menu. Choose Show SwiftUI Inspector and then you can edit the text/font properties.
SwiftUI lets you customize Text by applying a . font() modifier. The default iOS font is called San Francisco and if you don't explicitly change it, then all of your text will have the default iOS look. Some other options of standard fonts include: title, headline, subheadline, body, callout, caption or footnote.
SwiftUI comes with support for all of Dynamic Type's font sizes, all set using the . font() modifier. However, if you ask for a specific font and size, you'll find your text no longer scales up or down automatically according to the user's Dynamic Type settings – it remains fixed.
You can build your own view modifier. You can define what size and font you want to use for each of the UIFont.TextStyle inside private var fontDescriptions:
.
Now you can call this modifier on you Views like this. Text("my text").customFont(.headline)
Keep in mind, this one also implements the font scaling feature.
You could also call your "customFont" function "font" if you want to be hardcore.
extension View {
func customFont(_ textStyle: UIFont.TextStyle) -> ModifiedContent<Self, CustomFont> {
return modifier(CustomFont(textStyle: textStyle))
}
}
struct CustomFont: ViewModifier {
let textStyle: UIFont.TextStyle
/// Will trigger the refresh of the view when the ContentSizeCategory changes.
@Environment(\.sizeCategory) var sizeCategory: ContentSizeCategory
func body(content: Content) -> some View {
guard let fontDescription = fontDescriptions[textStyle] else {
print("textStyle nicht vorhanden: \(textStyle)")
return content.font(.system(.body));
}
let fontMetrics = UIFontMetrics(forTextStyle: textStyle)
let fontSize = fontMetrics.scaledValue(for: fontDescription.1)
return content.font(.custom(fontDescription.0, size: fontSize))
}
}
/// Define the custom fonts to use, depending on the TextStyle.
typealias CustomFontDescription = (String, CGFloat)
private var fontDescriptions: [UIFont.TextStyle: CustomFontDescription] = [
.headline: ("MYFONT", SIZE),
.subheadline: ("MYFONT", SIZE),
...
]
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