我在我的应用程序中使用TextStyles支持动态字体。我面临着为每个TextStyle更改Font的挑战。因此,例如TextStyle.body应该是MyAwesomeBODYFont,而TextStyle.headline应该是MyAwesomeHeadlineFont。而这对于整个应用程序而言。设置整个应用程序的字体将不起作用,因为我需要使用几种不同样式的字体。

是否可以使用整个应用程序的自定义字体而不是单独使用每个标签来覆盖这些TextStyles

我试过的

通常,为appearanceUILabel代理设置字体是可以的:

let labelAppearance = UILabel.appearance()
let fontMetrics = UIFontMetrics(forTextStyle: .body)
labelAppearance.font = fontMetrics.scaledFont(for: myAwesomeBodyFont)

但这会覆盖所有标签,无论它们使用什么TextStyle

之后,我尝试检查TextStyle,但它崩溃,UILabel.appearance()。font出现nil指针异常,甚至没有进入if块。
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)
}

因为UILabel的外观没有font设置。

最佳答案

您不能直接“设置”文本样式的自定义字体。
您可以获取文本样式的字体大小,然后可以使用自定义系列。

let systemDynamicFontDescriptor = UIFontDescriptor.preferredFontDescriptorWithTextStyle(UIFontTextStyleBody)
let size = systemDynamicFontDescriptor.pointSize
let font = UIFont(name: MyAwesomeBODYFont, size: size)

对于iOS 11+,有scaledFont()
您可以将此字体变量设为静态,并可以在应用程序中的任何地方使用它。

您也可以查看以下解决方案:https://stackoverflow.com/a/42235227/4846167

10-07 18:41