2010-04-21 95 views
25

如果UILabel包含太多文本,如何設置我的標籤以使其縮小字體大小?如何在UILabel縮小字體大小中製作文本

這裏是我如何設置我的UILabel:

 descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(200, 30, 130, 150)]; 
    [descriptionLabel setFont:[Utils getSystemFontWithSize:14]]; 
    [descriptionLabel setBackgroundColor:[UIColor clearColor]]; 
    [descriptionLabel setTextColor:[UIColor whiteColor]]; 
    descriptionLabel.numberOfLines = 1; 
    [self addSubview:descriptionLabel]; 

回答

58
descriptionLabel.adjustsFontSizeToFitWidth = YES; 
descriptionLabel.minimumFontSize = 10.0; //adjust to preference obviously 

下面的例子是測試和iPhone模擬器3.1.2驗證:

UILabel *descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(90, 0, 200, 30)]; 

descriptionLabel.font = [UIFont systemFontOfSize:14.0]; 
descriptionLabel.minimumFontSize = 10.0; 
descriptionLabel.adjustsFontSizeToFitWidth = YES; 
descriptionLabel.numberOfLines = 1; 
descriptionLabel.text = @"supercalifragilisticexpialidocious even thought he sound of it is something quite attrocious"; 
+0

我已經添加了這些行,但它似乎不工作。即使當我指定我的矩形是像CGRectMake(200,30,10,10)那樣小的東西時,也沒有任何反應。 – 2010-04-21 19:58:46

+0

我不確定你的[Utils getSystemFontWithSize:]正在返回什麼......我在編輯我的答案,以包含我剛剛測試和驗證的示例。 – prendio2 2010-04-21 20:24:29

+5

從iOS 6開始,您現在應該使用'setMinimumScaleFactor'而不是'minimumFontSize'。 – 2013-11-05 19:44:49

21

要調整在多行的UILabel文本,您可以使用此helper方法(基於code從11個像素工作室):

+ (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 >= minSize; 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:UILineBreakModeWordWrap]; 
    if(labelSize.height <= aLabel.frame.size.height) 
    break; 
} 
// Set the UILabel's font to the newly adjusted font. 
aLabel.font = font; 
} 
+0

在你的for循環中,條件應該是'i> = minSize',而不是'i> 10' – 2011-07-08 06:57:03

+0

你是對的..謝謝@chrispix。 – 2011-07-08 21:07:43

0

如果你想要的行數也增加,如果需要,可使用史蒂夫獅集團的解決方案,與if語句像這樣:

if(labelSize.height <= aLabel.frame.size.height) 
{ 
    aLabel.numberOfLines = labelSize.height/font.lineHeight; 

    break; 
} 
+3

或者只需將行數設置爲0。 – Jonathan 2012-10-30 00:48:18

相關問題