Search code examples
swiftmacoscocoanstextfield

NSTextField How to Set NSAttributedString's TextStyle property


I am trying to programmatically create a NSTextField that has the NSFont.TextStyle.headline font style. This font can also be set from the font drop down menu in the storyboard.

However, when I do the following:

let attributes: [NSAttributedString.Key : Any] = [NSAttributedString.Key.font : NSFont.TextStyle.headline]
let attributedString = NSAttributedString(string: product.url, attributes: attributes)
let textLabel = NSTextField(labelWithAttributedString: attributedString)

My app crashes with the following error:

-[__NSCFConstantString pointSize]: unrecognized selector sent to instance 0x7fff8064f918

Solution

  • We need to get the corresponding font associated with the text style.

    Pass these constants to preferredFont(forTextStyle:options:) or preferredFontDescriptor(forTextStyle:options:) to retrieve the corresponding font or font descriptor.

    Therefore:

    let attributes: [NSAttributedString.Key : Any] = [NSAttributedString.Key.font : NSFont.preferredFont(forTextStyle: NSFont.TextStyle.headline, options: [:])]