2013-01-07 51 views
0

我想縮小UILabel中的文本。我的文本是一個字符串,我有最多7行,有時不夠,那麼我需要縮小文本以適應7行。這裏我的代碼.`以編程方式收縮UIlabel中的文本

// 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];

我搞不​​清楚我做錯了什麼。我已經檢查了關於這個的所有帖子。

感謝所有幫助

回答

1

您可以使用一個輔助函數來調整其大小。 Here就是一個例子。我只是將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; 
} 
相關問題