gpt4 book ai didi

ios - 更改特定 UIFont.TextStyle 的所有 UILabels

转载 作者:行者123 更新时间:2023-11-29 05:57:43 25 4
gpt4 key购买 nike

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

是否可以使用整个应用程序的自定义字体(而不是单独为每个标签)以某种方式覆盖这些 TextStyles

我尝试过的:

设置 UILabelappearance 代理的字体通常效果很好:

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

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

之后,我尝试检查 TextStyle,但它因 UILabel.appearance().font 的 nil 指针异常而崩溃,或者甚至不进入 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)
}

因为UILabel的外观没有设置字体

最佳答案

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

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

关于ios - 更改特定 UIFont.TextStyle 的所有 UILabels,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54986678/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com