首页 > 解决方案 > UIFont 等宽数字 + 小型大写字母

问题描述

我正在尝试UIFont使用以下属性创建一个:

我正在使用系统字体 ( San Francisco),它确实支持所有这些功能。
据我所知,唯一的方法是使用多个UIFontDescriptor.

这是我正在使用的代码:

extension UIFont {

    var withSmallCaps: UIFont {
        let upperCaseFeature = [
            UIFontDescriptor.FeatureKey.featureIdentifier : kUpperCaseType,
            UIFontDescriptor.FeatureKey.typeIdentifier : kUpperCaseSmallCapsSelector
        ]
        let lowerCaseFeature = [
            UIFontDescriptor.FeatureKey.featureIdentifier : kLowerCaseType,
            UIFontDescriptor.FeatureKey.typeIdentifier : kLowerCaseSmallCapsSelector
        ]
        let features = [upperCaseFeature, lowerCaseFeature]
        let smallCapsDescriptor = self.fontDescriptor.addingAttributes([UIFontDescriptor.AttributeName.featureSettings : features])

        return UIFont(descriptor: smallCapsDescriptor, size: pointSize)
    }

    var withMonospacedDigits: UIFont {
        let monospacedDigitsFeature = [
            UIFontDescriptor.FeatureKey.featureIdentifier : kNumberSpacingType,
            UIFontDescriptor.FeatureKey.typeIdentifier : kMonospacedNumbersSelector
        ]
        let monospacedDigitsDescriptor = self.fontDescriptor.addingAttributes([UIFontDescriptor.AttributeName.featureSettings : [monospacedDigitsFeature]])

        return UIFont(descriptor: monospacedDigitsDescriptor, size: pointSize)
    }
}

通过这行代码,我应该能够获得具有前面提到的所有特征的字体:

let font = UIFont.systemFont(ofSize: 16, weight: .regular).withSmallCaps.withMonospacedDigits
// OR
let font = UIFont.monospacedDigitSystemFont(ofSize: 16, weight: .regular).withSmallCaps

但由于某些原因,它不起作用。我无法让字体在使用小写字母的同时具有等宽数字。

我究竟做错了什么?

标签: iosswiftuikituifontuifontdescriptor

解决方案


由于@Carpsen90链接的参考文档,我弄清楚了为什么它不起作用。

似乎该Number Spacing功能是专有的。

如文件所述:

功能分为“独占”和“非独占”。这表明是否可以一次选择给定特征类型内的多个不同选择器。因此,可以同时打开常见和稀有的连字,而不可能同时将给定的分数显示为垂直和对角线。

因此,同时拥有两个等宽数字 + 小型大写字母特征是不可能的。


编辑:

我误读了文件。该功能的选择器是专有的。但不是全部功能。所以应该是可以的。


推荐阅读