0

我正在尝试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

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

我究竟做错了什么?

4

2 回答 2

0

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

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

如文件所述:

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

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


编辑:

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

于 2018-08-16T19:58:38.713 回答
0

请查看参考文档以获取更多详细信息。我建议对除数字以外的所有字形使用带有小写字母的属性字符串,并为等宽数字使用另一种字体。这是一些示例代码:

let monoSpacedDigits = UIFont.systemFont(ofSize: 13, weight: .medium).withMonospacedDigits
let smallCaps = UIFont.systemFont(ofSize: 16, weight: .regular).withSmallCaps



let attributedString = NSMutableAttributedString(string: """
H3ll0 7here
1111111111
2222222222
3333333333
4444444444
5555555555
6666666666
7777777777
8888888888
9999999999
0000000000
""", attributes: [NSAttributedStringKey.font : smallCaps])

do {
    let regex = try NSRegularExpression(pattern: "[0-9]")
    let range = NSRange(0..<attributedString.string.utf16.count)
    let matches = regex.matches(in: attributedString.string, range: range)
    for match in matches.reversed() {
        attributedString.addAttribute(NSAttributedStringKey.font, value: monoSpacedDigits, range: match.range)
    }
} catch {
    // Do error processing here...
    print(error)
}

myLabel.attributedText = attributedString

我使用了 13 的大小和中等重量,以使等宽数字看起来与小型大写字母尽可能相似。

于 2018-08-16T19:08:04.107 回答