【问题标题】:UILabel Multiline Text Scale Font To Fit With \nUILabel 多行文本缩放字体以适应 \n
【发布时间】:2013-11-29 00:24:51
【问题描述】:

所以我试图让一些文字适合 我已经使用来自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;
    }
}

在我看来,文本已被缩放以适合 1 行上的所有文本,就好像硬换行符不存在一样。有没有办法让 UILabel 知道有一个换行符并相应地缩放行文本?

谢谢

【问题讨论】:

    标签: ios iphone objective-c uilabel


    【解决方案1】:

    您可以使用RTLabel 而不是UILabel, 并将换行符替换为html 的<br> 标签。 喜欢:

    RTLabel *label = [[RTLabel alloc] initWithFrame:/*your frame*/];
    NSString htmlText = [yourText stringByReplacingOccurrencesOfString:@"\\n" withString:@"<br>"];
    [label setText:htmlText];
    [yourView addSubView:label];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-07
      相关资源
      最近更新 更多