【问题标题】:Bold dynamic type in SwiftSwift 中的粗体动态类型
【发布时间】:2021-06-02 22:58:13
【问题描述】:

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

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

【问题讨论】:

    标签: swift accessibility dynamic-type-feature


    【解决方案1】:

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

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

    第 2 步: 在 info.plist 文件中的“应用程序提供的字体”键下添加这些字体

    第3步:如下使用。

    粗体:

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

    对于常规字体:

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

    【讨论】:

    • 不能使用系统字体吗?
    • 是的,您可以使用它。对于粗体:artistLabel.font = UIFont.boldSystemFont(ofSize: 12) 对于常规 artistLabel.font = UIFont.systemFont(ofSize: 12)
    【解决方案2】:

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

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

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

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

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

    您可以使用@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)
        }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-09
      • 2018-01-29
      • 1970-01-01
      • 2017-08-03
      • 2018-10-24
      • 1970-01-01
      • 2010-10-16
      • 1970-01-01
      相关资源
      最近更新 更多