UILabel多行文本缩放字体以适合\ n

时间:2013-11-29 00:24:52

标签: ios iphone objective-c uilabel

所以我想尝试一些文字 我使用Resizing UILabel to fit with Word Wrap的答案来使文字合适。这似乎有效,除了文本按比例缩小,只占屏幕宽度的50%左右。

这是在显示视图控制器时运行的代码:

self.user.title = @"Jeffrey C. Louie\n2326 Rockford Road\nCharlestown, MA 02129";
[self.titleLabel setText:self.user.title];

NSInteger fsize = 200;
[self.titleLabel setFont:[UIFont fontWithName:self.titleLabel.font.fontName size:fsize]];

float height = [self.user.title sizeWithFont:self.titleLabel.font constrainedToSize:CGSizeMake(self.titleLabel.bounds.size.width, 99999) lineBreakMode:NSLineBreakByWordWrapping].height;

while (height > self.titleLabel.bounds.size.height && height != 0) {
    fsize -=1;
    [self.titleLabel setFont:[UIFont fontWithName:self.titleLabel.font.fontName size:fsize]];
    height = [self.user.title sizeWithFont:self.titleLabel.font constrainedToSize:CGSizeMake(self.titleLabel.bounds.size.width, 99999) lineBreakMode:NSLineBreakByWordWrapping].height;
}

for (NSString *word in [self.user.title componentsSeparatedByString:@" "]) {
    float width = [word sizeWithFont:self.titleLabel.font].width;
    while (width > self.titleLabel.bounds.size.width && width != 0) {
        fsize -= 3;
        [self.titleLabel setFont:[UIFont fontWithName:self.titleLabel.font.fontName size:fsize]];
        width = [word sizeWithFont:self.titleLabel.font].width;
    }
}

example of text not fitting the view correctly

在我看来,文本已经缩放以适合1行上的所有文本,就好像硬线断开不存在一样。有没有办法让UILabel知道行换文的换行符和缩放比例?

由于

1 个答案:

答案 0 :(得分:0)

您可以使用RTLabel代替UILabel, 并将新行字符替换为<br>的{​​{1}}标记。 像:

html