简体   繁体   English

根据内容长度修改 NSTextField 的字体大小

[英]Modifying an 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,我有一个多行的NSTextField ,我需要设置它的字体大小,以便当它的内容很短时,它只显示在一个大字体大小的行上,
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.我查看了Get NSTextField contents to scale中提供的解决方案,但它不适用于多行字段。

I used this approach for changing the font size of a multi-line label.我使用这种方法来更改多行 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.基本上,如果字符串的长度太长,则减小字体大小以使其适合 label 区域。 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.其中theText是一个 NSString 并且label是我的多行 label 我希望将文本显示给用户。 The dimensions of the label is a fixed size. label 的尺寸是固定尺寸。

There's no native solution to dynamic font in NSTextField. 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让我们等待是否有人知道第三方开源代码可以优雅地做到这一点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM