Thursday, 16 August 2018

UIFont monospaced digits + small caps

I'm trying to create a UIFont with the following attributes:

  • Upper Case Small Caps
  • Lower Case Small Caps
  • Monospaced Digits

As far as I know, the only way to do it is to use multiple UIFontDescriptor.

Here is the code I'm using:

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)
    }
}

I should be able to obtain a font with all the characteristics mentioned earlier with this line of code:

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

But for some reasons, it does not work. I can't get the font to have monospaced digits while having small caps at the same time.

What am I doing wrong?



from UIFont monospaced digits + small caps

No comments:

Post a Comment