I'm using TextStyles in my app to support dynamic fonts. I have the challenge to change the Font for each TextStyle. So for example the TextStyle.body should be MyAwesomeBODYFont and the TextStyle.headline should be MyAwesomeHeadlineFont. And this for the entire app. Setting the font for the whole app won't work because I need several Fonts for the different styles.
Is it possible to override these TextStyles somehow with custom fonts for the entire app and not for each label separately?
What I tried:
Setting the font for the appearance proxy of UILabel in general works fine:
let labelAppearance = UILabel.appearance()
let fontMetrics = UIFontMetrics(forTextStyle: .body)
labelAppearance.font = fontMetrics.scaledFont(for: myAwesomeBodyFont)
But this overrides all labels not matter what TextStyle they use.
After that I tried to check for the TextStyle but it crashes with a nil pointer exception for the UILabel.appearance().font or does not even go into the if-block.
let labelAppearance = UILabel.appearance()
if let textStyle = labelAppearance.font.fontDescriptor.object(forKey: UIFontDescriptor.AttributeName.textStyle) as? UIFont.TextStyle {
// this would be the place to check for the TextStyle and use the corresponding font
let fontMetrics = UIFontMetrics(forTextStyle: textStyle)
labelAppearance.font = fontMetrics.scaledFont(for: mayAwesomeBodyFont)
}
Because the appearance of UILabel does not have a font set.