I want to programatically create an NSTextView. How can I determine the correct frame height so that the view displays one line of text in the current default font?

+3  A: 

The NSFont class has a method that can give you the size of a rectangle that would enclose a specific attributed string. Get the font used by your text view, create a string that serves as a reasonable example of what will be in the text view, and use that to inform your frame height. (The frame height will need to be some number of points larger than the actual rectangle the string would be displayed in.)

Alternately, you can get the various metrics from the font and attempt to calculate a reasonable frame from that. That might or might not work; for example, a font like Apple Chancery has a huge amount of variation depending on the glyphs that are being rendered, where they are in a word, and so on; I don't know that you can calculate what the needed size would be in advance without knowing exactly what you were going to render.

Chris Hanson
+2  A: 

It would be more normal to be using an NSTextField than an NSTextView for a single line of text.

With NSTextField, just do the following:

[textField setFont:myFont];
[textField sizeToFit];

Oh, and there is no built-in 'current default font'. If an application has such a concept, it needs to track it itself. The font panel doesn't read or write to anything global, it's used to operate on specific text objects.

There is the system font, which may be what he meant.
Peter Hosey