Typesetting a font in small caps on iOS

后端 未结 2 1713
情书的邮戳
情书的邮戳 2020-12-24 09:06

On iOS, I load a custom font in my project by adding its file name (an .otf file) to the info.plist file and then using this line of code:

UIFont myF

2条回答
  •  难免孤独
    2020-12-24 10:00

    Extension for UIFont in Swift:

    extension UIFont {
    
        func smallCaps() -> UIFont {
    
            let settings = [[UIFontFeatureTypeIdentifierKey: kLowerCaseType, UIFontFeatureSelectorIdentifierKey: kLowerCaseSmallCapsSelector]]
            let attributes: [String: AnyObject] = [UIFontDescriptorFeatureSettingsAttribute: settings, UIFontDescriptorNameAttribute: fontName]
    
            return UIFont(descriptor: UIFontDescriptor(fontAttributes: attributes), size: pointSize)
        }
    }
    

    Usage:

    label.font = UIFont(name: "SourceSansPro-Regular", size: 12)?.smallCaps()
    

    Example:

    macOS version:

    extension NSFont {
        func smallCaps() -> NSFont? {
            let settings = [[NSFontFeatureTypeIdentifierKey: kLowerCaseType, NSFontFeatureSelectorIdentifierKey: kLowerCaseSmallCapsSelector]]
            let attributes: [String: AnyObject] = [NSFontFeatureSettingsAttribute: settings as AnyObject, NSFontNameAttribute: fontName as AnyObject]
    
            return NSFont(descriptor: NSFontDescriptor(fontAttributes: attributes), size: pointSize)
        }
    }
    

    IMPORTANT:

    • not every font works with it, It's dependent on whether those characters are included in the font or not as @Anthony Mattox said.

    • remember to set the string as: Example, not EXAMPLE.

    • settings are Array, not NSDictonary.

提交回复
热议问题