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),
...
]