Iphone 以编程方式收缩UIlabel中的文本

Iphone 以编程方式收缩UIlabel中的文本,iphone,uilabel,xcode4.5,Iphone,Uilabel,Xcode4.5,我试图缩小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]; de

我试图缩小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]

我不知道我做错了什么。我已经检查了所有关于这个的帖子


感谢您的帮助

据我所知,UILabel不支持在多行模式下自动计算字体大小。你可以反复调整字体大小直到合适为止

也看看


您可以使用辅助功能调整其大小。这就是一个例子。我只是将lineBreakMode更改为NSLineBreakByWordWrapping(因为之前的版本在iOS6中被弃用)

+(void)resizeFontForLabel:(UILabel*)aLabel maxSize:(int)maxSize minSize:(int)minSize
{
//使用提供标签上的字体,这样我们就不会丢失颜色、样式等
UIFont*font=aLabel.font;
//从maxSize开始,不断缩小,直到它无法剪裁为止
对于(int i=maxSize;i>10;i--){
font=[font fontWithSize:i];
CGSize constraintSize=CGSizeMake(aLabel.frame.size.width,MAXFLOAT);
//此步骤检查标签的高度是否符合所需字体。
CGSize labelSize=[aLabel.text sizeWithFont:font constrainedToSize:ConstrainetSize lineBreakMode:NSLineBreakByWordWrapping];
if(labelSize.height
+ (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;
}