Found it. This answer was close, but wouldn't do it - had to access the textStorage object of the NSTextView first:
[[myNSTextView textStorage] setFont:[NSFont fontWithName:@"Menlo" size:11]];
Could someone explain to me what are the main differences between NSTextField and NSTextView? I know that NSTextView has more features and is usually used for longer texts, and NSTextField is usually used for one-line plain text fields, but if I understand correctly, NSTextField can be also used with attributed strings and with multiple lines...
Technically true, but you normally use text fields for values that are plain text and usually only one line. (Handle multiple lines, as a text field can accept them. If nothing else, strip the line breaks in a way that makes sense for what you're doing with the text.)
- it should display text in about 1-4 lines
NSTextView.
NSTextView. Supporting links in an NSTextField is tricky.
- it should let the user select and copy the text
Either will work for this.
- it should NOT let the user scroll the text,
NSTextField or NSTextView without NSScrollView. You can do the latter in IB by dragging a text view from the Library and then choosing “Unembed Objects” from the Layout menu.
edit the text,
Either will work for this.
or show the context menu that usually appears in editable text fields,
Yes, it should. You should always offer menu items like “Copy” and read-only services. Either control should do this for you; don't fight this.
it shouldn't even show a text cursor in this field
Either will work for this.
If you leave selection enabled (which you generally should), they'll show a cursor if the user clicks in the field. This is a feature, as it indicates where the selection anchor is for shift-⌘-arrow selection.
With such requirements, is it better for me to use a NSTextField or NSTextView?
I would use NSTextView.
Best Answer
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.