Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a bold UIFont from a regular UIFont?

Tags:

ios

uikit

ios5

If I have a UIFont object, is it possible to convert it to bold? I don't know the font name, I just have a UIFont object. What I want is a function like

UIFont *boldFontFromFont(UIFont *input)
{
    return [input derivedFontWithFontWeight:UIFontWeightBold];
}

How can I change the code so that it works. (The code above does not work, I just made it up to illustrate the point.)

Thanks in advance.

like image 546
Michael Avatar asked Apr 15 '13 13:04

Michael


3 Answers

iOS 7 introduces a new UIFontDescriptor class, which makes it a lot easier:

UIFont *font = [UIFont fontWithName:@"Helvetica Neue" size:12];
NSLog(@"plain font: %@", font.fontName); // “HelveticaNeue”

UIFont *boldFont = [UIFont fontWithDescriptor:[[font fontDescriptor] fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitBold] size:font.pointSize];
NSLog(@"bold version: %@", boldFont.fontName); // “HelveticaNeue-Bold”

UIFont *italicFont = [UIFont fontWithDescriptor:[[font fontDescriptor] fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitItalic] size:font.pointSize];
NSLog(@"italic version: %@", italicFont.fontName); // “HelveticaNeue-Italic”

UIFont *boldItalicFont = [UIFont fontWithDescriptor:[[font fontDescriptor] fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitBold | UIFontDescriptorTraitItalic] size:font.pointSize];
NSLog(@"bold & italic version: %@", boldItalicFont.fontName); // “HelveticaNeue-BoldItalic”

For people who got here looking for a Cocoa (macOS) equivalent, UIFontDescriptor comes from NSFontDescriptor, available since 10.3.

like image 88
marcprux Avatar answered Oct 20 '22 23:10

marcprux


And if you are looking for the swift implementation:

let normalFont = UIFont(name: "FONT_NAME", size: CGFloat(20))!
let boldFont = UIFont(descriptor: normalFont.fontDescriptor.withSymbolicTraits(.traitBold)!, size: normalFont.pointSize)

Hope this helps! Cheers!

like image 28
David H. Avatar answered Oct 20 '22 23:10

David H.


To get a bold font you need to pass a specific name of the font from a font family. You can get a font family name from a given font, then list all fonts from this family. In general, a bold font will contain "bold" in its name, but the format isn't strict and there could be variations like "Helvetica-BoldOblique", for example. You can start from this code:

- (UIFont *)boldFontFromFont:(UIFont *)font
{
    NSString *familyName = [font familyName];
    NSArray *fontNames = [UIFont fontNamesForFamilyName:familyName];
    for (NSString *fontName in fontNames)
    {
        if ([fontName rangeOfString:@"bold" options:NSCaseInsensitiveSearch].location != NSNotFound)
        {
            UIFont *boldFont = [UIFont fontWithName:fontName size:font.pointSize];
            return boldFont;
        }
    }
    return nil;
}
like image 14
filwag Avatar answered Oct 20 '22 23:10

filwag