2011-01-22 29 views
2

在我的iPad應用程序中,我有一個標籤,佔據整個視圖。我想動態計算適合整個矩形的標籤大小。但我想保持這個詞包裝。 在我的XIB中,我添加了一個標籤並將其設置爲自動換行模式。iPad/iPhone - 設置適合給定矩形的標籤大小

查看所附圖片。我想要的是用自動換行顯示標籤。有人能幫我找到問題嗎?

下面是我使用的代碼: (在這些論壇中的答案之一,我發現下面的代碼:)

-(void)sizeLabel:(UILabel*)label toRect:(CGRect)labelRect withFont:(NSString*)fontName { 

    // Set the frame of the label to the targeted rectangle 
    label.frame = labelRect; 

    // Try all font sizes from largest to smallest font size 
    int fontSize = 300; 
    int minFontSize = 5; 

    // Fit label width wize 
    CGSize constraintSize = CGSizeMake(label.frame.size.width, MAXFLOAT); 

    do { 
    // Set current font size 
    label.font = [UIFont fontWithName:fontName size:fontSize]; 

    // Find label size for current font size 
    CGSize labelSize = [[label text] sizeWithFont:label.font 
     constrainedToSize:constraintSize 
     lineBreakMode:UILineBreakModeWordWrap]; 

    // Done, if created label is within target size 
    if(labelSize.height <= label.frame.size.height) 
    break; 

    // Decrease the font size and try again 
    fontSize -= 2; 

    } while (fontSize > minFontSize); 
} 

alt text

回答

2

所以你想了解我要包裝的文字,但最大可能的大小? 在這種情況下,這樣做:

//With the line break mode set to wordwrap and number of lines set to 1. 
[label adjustsFontSizeToFitWidth:YES]; 
//set max font 
label.font = [UIFont fontWithName:fontName 300]; 
[label setMinimumFontSize:5]; 

這應該是所有你需要做的。

+0

第一行代碼應該是[label setAdjustsFontSizeToFitWidth:YES]; – 2014-03-07 06:57:51

相關問題