开发者

Detect whether a font is bold/italic on iOS?

Given a UIFont or a CTFo开发者_开发问答nt, how can I tell whether the font is bold/italic?


iOS7 Font Descriptor

No reason to use Core Text, you can simply ask UIFont for the fontDescriptor.

        UIFont *font = [UIFont boldSystemFontOfSize:17.0f];
        UIFontDescriptor *fontDescriptor = font.fontDescriptor;
        UIFontDescriptorSymbolicTraits fontDescriptorSymbolicTraits = fontDescriptor.symbolicTraits;
        BOOL isBold = (fontDescriptorSymbolicTraits & UIFontDescriptorTraitBold) != 0;

Going forward this is probably the easiest way to ask about the traits of a font.


If you want to do this with Swift:

extension UIFont {
    var isBold: Bool {
        return fontDescriptor.symbolicTraits.contains(.traitBold)
    }
    
    var isItalic: Bool {
        return fontDescriptor.symbolicTraits.contains(.traitItalic)
    }
}

Usage:

let font: UIFont = UIFont.preferredFont(forTextStyle: .headline)
if font.isBold {
  print("it's bold..")
}


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


Answer for Swift 3/4 based on Arjan's answer:

extension UIFont {
    var isBold: Bool {
        return fontDescriptor.symbolicTraits.contains(.traitBold)
    }

    var isItalic: Bool {
        return fontDescriptor.symbolicTraits.contains(.traitItalic)
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜