Swift 中的粗体动态类型

Bold dynamic type in Swift

为什么要在 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

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

您可以为此使用自定义字体。

步骤 1: 将自定义字体添加到项目。

步骤 2: 在 info.plist 文件

中的“应用程序提供的字体”键下添加这些字体

第 3 步:按如下方式使用。

对于粗体字体:

artistLabel.font = UIFont(name:"ArchSans-Bold", size: fontSize)

常规字体:

artistLabel.font = UIFont(name:"ArchSans", size: fontSize)

bold and regular look the same?

你这样说是因为我认为你误用元素传入了preferredFont方法的传入参数compatibleWith
您已根据需要提供了一个 UITraitCollection 元素,这就是您的代码编译的原因。
很好,但是 此特征必须是内容大小类别 才能被系统很好地理解 ⟹ Apple doc

你应该这样使用指定的方法,例如:

artistLabel.font = UIFont.preferredFont(forTextStyle: .body,
                                        compatibleWith: UITraitCollection(preferredContentSizeCategory: .large))

How can I get a true "bold" font?

您可以使用@Ritupal 提供的高效代码,也可以尝试从 WWDC 2020 视频中提取的以下代码 (The details of UI typography) 来获得更强调的文字样式:

if let artistDescriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: .body).withSymbolicTraits(.traitBold) {
        
        artistLabel.font = UIFont(descriptor: artistDescriptor,
                                  size: 0.0)
    }

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