Detect whether a font is bold/italic on iOS?

前端 未结 4 1325
眼角桃花
眼角桃花 2020-12-15 06:21

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

相关标签:
4条回答
  • 2020-12-15 06:21

    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);
    
    0 讨论(0)
  • 2020-12-15 06:21

    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.

    0 讨论(0)
  • 2020-12-15 06:34

    If you want to do this with Swift 2.0:

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

    Usage:

    let font: UIFont = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
    if font.isBold {
      print("it's bold..")
    }
    
    0 讨论(0)
  • 2020-12-15 06:45

    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 讨论(0)
提交回复
热议问题