【发布时间】:2019-07-25 23:14:26
【问题描述】:
我在我的应用程序中使用TextStyles 来支持动态字体。我面临为每个TextStyle 更改字体的挑战。例如,TextStyle.body 应该是 MyAwesomeBODYFont,TextStyle.headline 应该是 MyAwesomeHeadlineFont。这适用于整个应用程序。为整个应用设置字体将不起作用,因为我需要为不同样式设置多个字体。
是否可以以某种方式为整个应用程序而不是为每个标签单独使用自定义字体覆盖这些TextStyles?
我尝试了什么:
为UILabel 的appearance 代理设置字体通常可以正常工作:
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 集。
【问题讨论】:
-
您不能直接“设置”文本样式的自定义字体。我建议搜索
dynamic type custom font- 你会找到很多资源。这是一个开始的地方:useyourloaf.com/blog/using-a-custom-font-with-dynamic-type -
感谢搜索推荐!我实际上已经搜索了确切的术语并使用了这篇文章 :) 我稍微指定了我的问题。
-
TypographyKit 是一个可以帮助解决这个问题的第三方模块。
-
TypographyKit 在我发现它时听起来很有趣,但它也为每个标签设置了这个。用户界面组件。无论如何感谢您的评论,我再次查看了框架,但找不到针对该特定问题的解决方案。
标签: ios swift cocoa-touch