iosuifont

Detect whether a font is bold/italic on iOS?


Given a UIFont or a CTFont, how can I tell whether the font is bold/italic?


Solution

  • Looking at the font's name won't always work. Consider the font "Courier Oblique" (which is italic) or "HoeflerText-Black" (which is bold), Neither of those contain "bold" or "italic" in their names.

    Given a font as a CTFontRef, the proper way to determine whether it's bold or italic is to use the CTFontGetSymbolicTraits function:

    CTFontRef font = CTFontCreateWithName((CFStringRef)@"Courier Oblique", 10, NULL);
    CTFontSymbolicTraits traits = CTFontGetSymbolicTraits(font);
    BOOL isItalic = ((traits & kCTFontItalicTrait) == kCTFontItalicTrait);
    BOOL isBold = ((traits & kCTFontBoldTrait) == kCTFontBoldTrait);
    NSLog(@"Italic: %i Bold: %i", isItalic, isBold);
    CFRelease(font);