Michael Michael - 6 months ago 54
iOS Question

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

If I have a

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.


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;