swiftnsfont

Check if NSFont is bold in Swift


I am writting unit test checking the format of a generated NSAttributedString.

I can extract the font like this:

if let font = attributedString.attributesAtIndex(0, effectiveRange: nil) as? NSFont {
    ...
}

Given this NSFont instance, how can I check if it is bold or not?


Solution

  • You can check your font traits like this:

    let descriptor = font.fontDescriptor
    let symTraits = descriptor.symbolicTraits
    let traitSet = NSFontTraitMask(rawValue: UInt(symTraits))
    let isBold = traitSet.contains(.BoldFontMask))
    

    But I'm not sure if isBold would be true for all seemingly-bold fonts.