4

I have a multi-line NSTextField and I need to set its font size so that when its content is short, it displays only on one line with a big font size,
but when it's content is longer, it splits to two lines and also shrinks its font size, so that the content will stay in its bounds.

I've looked at the solution provided in Get NSTextField contents to scale, but it doesn't work with multi-line fields.

Jon Schneider
  • 25,758
  • 23
  • 142
  • 170
Mikk Rätsep
  • 512
  • 7
  • 20
  • 1
    You could also use the system constants similar to this example: `textField.font = [NSFont systemFontOfSize:[NSFont smallSystemFontSize]];` – JJD Oct 02 '12 at 15:27

2 Answers2

5

I used this approach for changing the font size of a multi-line label. Basically, if the length of the string is too long, then the font size is decreased to make it fit inside the label area. Hope this helps.

if ([theText length] > 64) {
        [label setFont:[NSFont systemFontOfSize:10]];
    } else {
        [label setFont:[NSFont systemFontOfSize:13]];
    }

Where theText is an NSString and the label is my multi-line label where I want the text to be displayed to the user. The dimensions of the label is a fixed size.

wigging
  • 8,492
  • 12
  • 75
  • 117
  • Thanks for a good idea, but i've used a loop, that increases the fonts size until it doesn't fit anymore - because i needed it to be a bit more dynamical, without couple of fixed values. – Mikk Rätsep Mar 02 '12 at 09:50
1

There's no native solution to dynamic font in NSTextField. You'd have to build your own algorithm.

EDIT:

It might not be too difficult. You'd probably just have to subclass it, then do a method that do (in pseudocode):

if(text.length > someValue) 
    self.fontSize = 17 
else if (text.length < someValue)
    self.fontSize = 14
else
   self.fontSize = 12

Let's wait if someone know a third party open source code to do this elegantly

Enrico Susatyo
  • 19,372
  • 18
  • 95
  • 156
  • that I feared. But the question stays the same, only does anyone know a good algorithm that I might use/be able to modify to work on my case. – Mikk Rätsep Jun 29 '11 at 12:05
  • Hmm you may be able to find something on github or wait for someone else to post it here. But I guess it won't be that difficult. See edit in my post in a bit. – Enrico Susatyo Jun 29 '11 at 12:10
  • What I have done is 1) find the longest word in your text 2) loop over increasing smaller font sizes and change the font of your NSTextField to that size 3) SizeToFit and if the NSTextField is "1" line high, you found your font size. 4) Use linebreakmodeWord so that no words are split up and since the longest word fits, it should look ok. – Larry Jul 09 '22 at 21:09