Setting BOLD font on iOS UILabel

It’s a fishy business to mess with the font names. And supposedly you have an italic font and you wanna make it bold – adding simply @"-Bold" to the name doesn’t work. There’s much more elegant way:

- (UIFont *)boldFontWithFont:(UIFont *)font
{
    UIFontDescriptor * fontD = [font.fontDescriptor
                fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitBold];
    return [UIFont fontWithDescriptor:fontD size:0];
}

size:0 means ‘keep the size as it is in the descriptor’.
You might find useful UIFontDescriptorTraitItalic trait if you need to get an italic font

In Swift it would be nice to write a simple extension:

extension UIFont {

    func withTraits(traits:UIFontDescriptorSymbolicTraits...) -> UIFont {
        let descriptor = self.fontDescriptor().fontDescriptorWithSymbolicTraits(UIFontDescriptorSymbolicTraits(traits))
        return UIFont(descriptor: descriptor, size: 0)
    }

    func bold() -> UIFont {
        return withTraits(.TraitBold)
    }

    func italic() -> UIFont {
        return withTraits(.TraitItalic)
    }

    func boldItalic() -> UIFont {
        return withTraits(.TraitBold, .TraitItalic)
    }

}

Then you may use it this way:

myLabel.font = myLabel.font.boldItalic()

myLabel.font = myLabel.font.bold()

myLabel.font = myLabel.font.withTraits(.TraitCondensed, .TraitBold, .TraitItalic)

Leave a Comment