UILabel and UIButton Font Kerning with Swift

Here’s an extension to UILabel that kerns it’s text with a specified kerning value.

extension UILabel {
    func kern(kerningValue:CGFloat) {
        self.attributedText =  NSAttributedString(string: self.text ?? "", attributes: [NSKernAttributeName:kerningValue, NSFontAttributeName:font, NSForegroundColorAttributeName:self.textColor])
    }
}

Usage:

mylabel.kern(1.5)

This extension to UIButton kerns the text in it’s titleLabel property.

extension UIButton {
    func kern(kerningValue:CGFloat) {
        let attributedText =  NSAttributedString(string: self.titleLabel!.text!, attributes: [NSKernAttributeName:kerningValue, NSFontAttributeName:self.titleLabel!.font, NSForegroundColorAttributeName:self.titleLabel!.textColor])
        self.setAttributedTitle(attributedText, forState: UIControlState.Normal)
    }
}

Usage:

mybutton.kern(1.5)

Note, as of XCode 6.2, the UIButton type must be custom so that the UIButton is resized with the kerned text. Resizing behavior occurs without a call to sizeToFit() or invalidateIntrinsicContentSize().

Leave a Reply

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