iOS Font Kerning with Swift and NSAttributedString

From Wikipedia –

In typography, kerning (less commonly mortising) is the process of adjusting the spacing between characters in a proportional font, usually to achieve a visually pleasing result.

Today I received a PSD with kerned fonts, so I created a type level method in Swift that lets me create an attributed string by specifying a kerning value.

class func attributedString(string text:String, withFont font:UIFont!, kerning: CGFloat!, andColor color:UIColor!) -> NSAttributedString?  {
    return NSAttributedString(string: text, attributes: [NSKernAttributeName:kerning, NSFontAttributeName:font, NSForegroundColorAttributeName:color])

Now lets say this method was in a class called “AppearanceService”, this usage would be like this:

let attributedText:NSAttributedString? = AppearanceService.attributedString(string: "Kern it, Kern it good.", withFont: AppearanceService.mediumFont(size: 15), kerning: 1.5, andColor: UIColor.whiteColor())

Leave a Reply

Your email address will not be published. Required fields are marked *