Swift Snippet: Small Caps UIFont variant extension

October 21, 2015

This extension uses CoreText's constants to produce a Small Caps UIFont variant by deriving the oritinal font's UIFontDescriptor.

extension UIFont {
    
    func smallCapsFontVariant(smallCapsForUppercase: Bool = true) -> UIFont {
        var features = [
            [UIFontFeatureTypeIdentifierKey: kLowerCaseType,
                UIFontFeatureSelectorIdentifierKey: kLowerCaseSmallCapsSelector]
        ]
        
        if smallCapsForUppercase {
            features.append([UIFontFeatureTypeIdentifierKey: kUpperCaseType,
                UIFontFeatureSelectorIdentifierKey: kUpperCaseSmallCapsSelector])
        }
        
        let smallCapsFontDescriptor = fontDescriptor().fontDescriptorByAddingAttributes([
            UIFontDescriptorFeatureSettingsAttribute : features
            ])
        
        return UIFont(descriptor: smallCapsFontDescriptor, size: 0)
    }
}