开发者

Modifying a multi-line NSTextField's font size according to content length

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 provi开发者_如何转开发ded in Get NSTextField contents to scale, but it doesn't work with multi-line fields.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜