Setting NSTextView Font Size Using Swift

March 18, 2020 · 2 min read

When setting the font size of an NSTextView things can get a bit weird with the Attributes Inspector in Xcode.

When there is no text in a text view you cannot set the font, sure you can click on the font icon to open the font panel and change it, but it will be ignored.

Xcode 11 Font Inspector

The only way to set it that I have found using the inspector is to put at least one character in the text box. Plus that still does not solve the problem, if you empty the text view at runtime it will reset back to the default. Not the behavior you are expecting right?

So the answer I have found is to ignore editing in the inspector all together and set the font properties using Swift. Yet another reason to ignore storyboard editing.

Here is the code I am using in my viewDidLoad to set the font for two NSTextViews I have in my view. Note that the font size is a CGFloat

@IBOutlet var pwContentField: NSTextView!
@IBOutlet var csContentField: NSTextView!
let contentFontSize: CGFloat  = 16
override func viewDidLoad() {

    csContentField.font = .systemFont(ofSize: contentFontSize)
    pwContentField.font = .systemFont(ofSize: contentFontSize)

There might be better or more accepted ways, but this solves the problem for me.

Subscribe to site
Peter Witham

Web and Mobile Software Maker, Photographer and Podcaster. I live and breath creativity.
I'd love for you to connect with me via Twitter or if you are a photo person like myself, Instagram.