Swift 中的粗体动态类型

Wis*_*uns 3 accessibility swift dynamic-type-feature

在此输入图像描述

为什么UILabel我们有以下动态字体:

        artistLabel.font = UIFont.preferredFont(forTextStyle: .body, compatibleWith: UITraitCollection(legibilityWeight: .regular))
        artistLabel.adjustsFontForContentSizeCategory = true
        
        trackLabel.font = UIFont.preferredFont(forTextStyle: .body, compatibleWith: UITraitCollection(legibilityWeight: .bold))
        trackLabel.adjustsFontForContentSizeCategory = true
Run Code Online (Sandbox Code Playgroud)

粗体和常规看起来一样吗?如何获得真正的“粗体”字体?

XLE*_*_22 8

\n

粗体和常规看起来一样吗?

\n
\n

您做出此声明是因为我认为您滥用该元素来传递方法compatibleWith的传入参数preferredFont
\n您已经提供了UITraitCollection所需的元素,这就是您的代码编译的原因。
\n这很好,但此特征必须是系统能够很好理解的内容大小类别\xe2\x9f\xb9 Apple 文档

\n

例如,您应该以这种方式使用指定的方法:

\n
artistLabel.font = UIFont.preferredFont(forTextStyle: .body,\n                                        compatibleWith: UITraitCollection(preferredContentSizeCategory: .large))\n
Run Code Online (Sandbox Code Playgroud)\n
\n

如何获得真正的“粗体”字体?

\n
\n

您可以使用 @Ritupal 提供的高效代码,也可以尝试从 WWDC 2020 视频UI 排版的详细信息中提取的以下代码来获得更强调的文本样式:

\n
if let artistDescriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: .body).withSymbolicTraits(.traitBold) {\n        \n        artistLabel.font = UIFont(descriptor: artistDescriptor,\n                                  size: 0.0)\n    }\n
Run Code Online (Sandbox Code Playgroud)\n

即使已经提供了解决方案,我认为补充这个答案以解释为什么您的初始代码不起作用,同时引入另一种方法来强调具有粗体特征的文本很重要。

\n