【发布时间】:2010-08-19 10:30:35
【问题描述】:
这是 iPhone 应用程序的一部分,但通常应该适用于用 objC 编写的 Cocoa。
我有一个 UILabel 包含不同数量的文本(从单个字符到几个句子)。文本应始终以适合 UILabel 中所有文本的最大可能字体显示。 最大行数设置为4,换行模式设置为自动换行。
由于使用了多行,adjustsFontSizeToFitWidth 无法调整文本大小。
因此我使用循环来确定每个字符串的最大可能字体大小:
//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; };
这种方法在大多数情况下效果很好。 长词除外。 让我们使用字符串@“体验 foo”。举个例子。 “经验”一词比其他词长得多,将在没有正确换行的情况下分成两半,字符串分成 4 行。 我正在寻找一种方法来进一步减小大小,以便每个单词都适合一行。
例子:
-老-
字体大小:60
The Exper ience foo
应该是
-新-
字体大小:30
The Experience foo
可能有一种简单的方法可以做到这一点,但我碰壁了。
【问题讨论】:
标签: iphone cocoa-touch uikit uilabel word-wrap