这是 iPhone 应用程序的一部分,但通常应该适用于用 objC 编写的 Cocoa。
我有一个 UILabel 保存各种数量的文本(从单个字符到几个句子)。文本应始终以适合 UILabel 中所有文本的尽可能大的字体显示。
最大行数设置为 4,换行模式设置为自动换行。
由于使用了多行,因此 adjustmentFontSizeToFitWidth 将无法用于调整文本大小。
因此,我使用循环来确定每个字符串的最大可能字体大小,如下所示:
//Set the text
self.textLabel.text = text;
//Largest size used
NSInteger fsize = 200; textLabel.font = [UIFont
fontWithName:@"Verdana-Bold"
size:fsize];
//Calculate size of the rendered string with the current parameters
float height = [text sizeWithFont:textLabel.font
constrainedToSize:CGSizeMake(textLabel.bounds.size.width,99999)
lineBreakMode:UILineBreakModeWordWrap].height;
//Reduce font size by 5 while too large, break if no height (empty string)
while (height > textLabel.bounds.size.height and height != 0) {
fsize -= 5;
textLabel.font = [UIFont fontWithName:@"Verdana-Bold" size:fsize];
height = [text sizeWithFont:textLabel.font
constrainedToSize:CGSizeMake(textLabel.bounds.size.width,99999)
lineBreakMode:UILineBreakModeWordWrap].height;
};
这种方法在大多数情况下都很有效。
长单词除外。
让我们以字符串@“The experience foo”为例。举个例子。
“experience”这个词比其他词长得多,如果没有正确换行,它就会被分成两半,并且字符串会被分成 4 行。
我正在寻找一种进一步减小大小的方法,以便每个单词都适合一行。
Example:
-old-
字体大小:60
The
Exper
ience
foo
应该
-new-
字体大小:30
The
Experience
foo
可能有一种简单的方法可以做到这一点,但我遇到了困难。
这是我发现的最优雅(但有点黑客)的方法:
- 将字符串拆分为单词
- 使用当前字体大小计算每个单词的宽度
- 减小字符串的大小,直到每个单词都适合一行
资源消耗足够低,即使在UITableViews
充满了这样编辑的字符串。
这是新代码:
//Set the text
self.textLabel.text = text;
//Largest size used
NSInteger fsize = 200; textLabel.font = [UIFont fontWithName:@"Verdana-Bold"
size:fsize];
//Calculate size of the rendered string with the current parameters
float height =
[text sizeWithFont:textLabel.font
constrainedToSize:CGSizeMake(textLabel.bounds.size.width,99999)
lineBreakMode:UILineBreakModeWordWrap].height;
//Reduce font size by 5 while too large, break if no height (empty string)
while (height > textLabel.bounds.size.height and height != 0) {
fsize -= 5;
textLabel.font = [UIFont fontWithName:@"Verdana-Bold" size:fsize];
height = [text sizeWithFont:textLabel.font
constrainedToSize:CGSizeMake(textLabel.bounds.size.width,99999)
lineBreakMode:UILineBreakModeWordWrap].height;
};
// Loop through words in string and resize to fit
for (NSString *word in [text componentsSeparatedByString:@" "]) {
float width = [word sizeWithFont:textLabel.font].width;
while (width > textLabel.bounds.size.width and width != 0) {
fsize -= 3;
textLabel.font = [UIFont fontWithName:@"Verdana-Bold" size:fsize];
width = [word sizeWithFont:textLabel.font].width;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)