NSFont(name:size:) not working for all fonts

776 Views Asked by At

I am trying to set the font and font size for an NSTextField.

For some fonts, this works as expected, but for other fonts, only the font is set, and the size is ignored (it is set to some small, default size).

The stringValue of the NSTextField is a string of Chinese characters, e.g. .

class ViewController: NSViewController {
    @IBOutlet weak var displayLabel: NSTextField!
    ...
    override func viewDidLoad() {
        super.viewDidLoad()
        self.displayLabel.font = NSFont(name: "Heiti TC Medium", size: CGFloat(128.0))
        ...
    }
    ....
}

For the font "Heiti TC Medium", I can set the size, but for "BiauKai Ordinary", I just get the small, default size.

In the macOS Font Book app, I can set the size for both fonts, and that works as expected, so it should not be an issue with the font itself.

Update:

As it turns out, with the small font size, it's hard to see if the font actually changes. I think maybe I made a mistake in thinking they did.

The only safe way of dealing with the fonts, because you apparently don't get an error if the system can't identify the font, is to query the system for the font name, as pointed out in the link by Guy Kogus below.

1

There are 1 best solutions below

3
Guy Kogus On

Getting the exact font name can be a pain sometimes. What I often do to debug this is put a breakpoint somewhere and see what fonts are available through the debugger, by calling:

(lldb) po UIFont.familyNames

and then once you find the correct family, BiauKai (or whatever it's called in that last) get the exact names by calling

(lldb) po UIFont.fontNames(forFamilyName: "BiauKai")