Ios – Setting BOLD font on iOS UILabel

fontsiosobjective cuifont

I have assigned a custom font of 'Helvetica' with size 14 already for the text in UILabel using Interface Builder.

I am using reusing the same label at multiple places, but at some place I have to display the text in bold.

Is there any way I can just specify to make the existing font bold instead of creating the whole UIFont again? This is what I do now:

myLabel.font = [UIFont fontWithName:@"Helvetica Neue" size:14];

Best Answer

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)