6

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?

Martin Delille
  • 11,360
  • 15
  • 65
  • 132

2 Answers2

7

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.

OOPer
  • 47,149
  • 6
  • 107
  • 142
2

Updated answer for Swift 4 and with an NSFont extension:

extension NSFont {
    var isBold: Bool {
        return fontDescriptor.symbolicTraits.contains(.bold)
    }
}
LuisCien
  • 6,362
  • 4
  • 34
  • 42