0

我正在尝试缩小 UILabel 中的文本。我的文本是一个字符串,我最多有 7 行,有时还不够,然后我需要缩小文本以适应这 7 行。这是我的代码。`

// create label
    UILabel *desc = [[UILabel alloc] initWithFrame:CGRectMake(5, 220, 310, 200)];
    desc.backgroundColor = [UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1];
    desc.font = [UIFont fontWithName:@"Helvetica" size:30];
    desc.numberOfLines = 7;
    desc.textColor = [UIColor blackColor];
    desc.layer.borderColor = [UIColor blackColor].CGColor;
    desc.layer.borderWidth = 1.0;
    desc.text = // MY string ;
    desc.adjustsFontSizeToFitWidth = YES;
    [self.view addSubview:desc];`

我什至尝试过[desc sizeToFit]

我无法弄清楚我做错了什么。我已经检查了所有关于此的帖子。

谢谢你的帮助

4

2 回答 2

1

您可以使用辅助函数来调整它的大小。 是一个例子。我只是将 lineBreakMode 更改为 NSLineBreakByWordWrapping (因为以前在 iOS6 中已弃用)。

+ (void)resizeFontForLabel:(UILabel*)aLabel maxSize:(int)maxSize minSize:(int)minSize
{
    // use font from provided label so we don't lose color, style, etc
    UIFont *font = aLabel.font;

    // start with maxSize and keep reducing until it doesn't clip
    for(int i = maxSize; i > 10; i--) {
        font = [font fontWithSize:i];
        CGSize constraintSize = CGSizeMake(aLabel.frame.size.width, MAXFLOAT);

        // This step checks how tall the label would be with the desired font.
        CGSize labelSize = [aLabel.text sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
        if(labelSize.height <= aLabel.frame.size.height)
            break;
    }
    // Set the UILabel's font to the newly adjusted font.
    aLabel.font = font;
}
于 2013-01-07T02:02:28.153 回答
0

据我所知,UILabel 不支持在多行模式下自动计算字体大小。您可以迭代字体大小,直到它适合。

也看看

sizeWithFont:forWidth:lineBreakMode:

于 2013-01-07T01:15:06.870 回答