在UILabel中启用小写字体

时间:2018-10-25 16:51:33

标签: ios uilabel core-text typography

我正在尝试在UILabel中启用小写字母功能。这个问题已经被问过很多次了,答案很简单:

override func awakeFromNib() {
  super.awakeFromNib()

  let fontSize: CGFloat = 24
  let descriptor = UIFont
    .systemFont(ofSize: 24)
    .fontDescriptor
    .addingAttributes([
      UIFontDescriptor.AttributeName.featureSettings: [
        UIFontDescriptor.FeatureKey.featureIdentifier: kLowerCaseType,
        UIFontDescriptor.AttributeName.featureSettings: kLowerCaseSmallCapsSelector
      ]
    ])

  titleLabel.font = UIFont(descriptor: descriptor, size: fontSize)
  titleLabel.text = "Welcome"
}

但是,此代码不起作用,我也不明白为什么。我有一些想法:

  1. 字体可能不包含小写字母字形。我怀疑这是问题所在,因为我正在使用系统字体。我尝试使用“ Helvetica Neue”以防万一,但没有成功。
  2. 使用UILabel.text属性设置文本时,不支持小写字体。但是,使用UILabel.attributedText属性不能解决问题。
  3. UILabel完全不支持小写字体。我尝试了UITextView,但是结果是一样的。
  4. 这可能是iOS 12的问题,但该问题也已在iOS 11.4上重现。

还有其他我可能会想念的东西吗?

2 个答案:

答案 0 :(得分:2)

进行了一些测试,并参考此要点(https://gist.github.com/juliensagot/8fc3e2e6b5ad1e14b3ecb394a417b010),看来您需要设置两者大小写功能,否则小写字母不起作用,至少在模拟器中的iOS 12下。测试了几种不同的字体。

let fontSize: CGFloat = 24.0
let fontDescriptor = UIFont.systemFont(ofSize: fontSize, weight: .medium).fontDescriptor

let upperCaseFeature = [
    UIFontDescriptor.FeatureKey.featureIdentifier : kUpperCaseType,
    UIFontDescriptor.FeatureKey.typeIdentifier : kUpperCaseType
 ]

let lowerCaseFeature = [
    UIFontDescriptor.FeatureKey.featureIdentifier : kLowerCaseType,
    UIFontDescriptor.FeatureKey.typeIdentifier : kLowerCaseSmallCapsSelector
]

let features = [upperCaseFeature, lowerCaseFeature]
let additions = fontDescriptor.addingAttributes([.featureSettings: features])

label.font = UIFont(descriptor: additions, size: fontSize)
label.text = "Hello There!"

模拟器截图:

Screenshot from the simulator

答案 1 :(得分:0)

我决定在一个新的项目中尝试我的代码,并且成功了。然后,我从笔尖中删除了titleLabel并添加了一个新代码,之后我的代码也可以在当前项目中使用。

这似乎是一些奇怪的缓存问题,还是先前的titleLabel上的某些设置与小写字体不兼容。