问题描述
如何在 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)
,
粗体和常规看起来一样吗?
您做出此声明是因为我认为您误用了元素来传入 compatibleWith
方法的传入参数 preferredFont
。
您已根据需要提供了 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)
}
即使已经提供了解决方案,我认为补充这个答案很重要,以解释为什么您的初始代码不起作用,同时带来了另一种方式来强调具有粗体特征的文本。 ?