Search code examples
cocoaxcode4nstextfield

Setting font size based on line height in NSTextField


I have an NSTextField where the font used can be changed by the user.

Although the font's point size remains the same, the actual height of the font is much bigger for some fonts. This means if the user changes the font to 'Zapfino' for example, most of the text is cropped. I would like it so the text in the box always looks roughly the same size.

Also the line height seems to change depending on which font is used meaning they don't line up well and sometimes get pushed down and the bottom gets cropped off.

How can I keep the text size and line height looking the same?


Solution

  • You need NSTextField which is using single line. You can do it in Attributes inspector by checking Uses Single Line Mode.

    How to do it:

    Single mode

    And now Your text will be like this:

    example

    Do programatically:

    To change NSTextField height programatically by font size or scale the text to fit the bounds example here.