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

后端 未结 7 1906
醉话见心
醉话见心 2020-12-08 19:08

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

<
7条回答
  •  再見小時候
    2020-12-08 19:58

    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;
    }
    

提交回复
热议问题