2014-02-13 40 views
0

我有一個UILabel其財產text我想設置段落文本使用NSStringiOS:找到正確的字體大小以適應UILabel,具體取決於其大小

我有一個數組,其中存儲了代表文本段落的字符序列。

該段落不必完全適合/包含在此UILabel內。如果段落沒有結束,我會轉到下一個標籤。

讓我們說,如果我有這個UILabel 160×240矩形的大小,我怎麼可能能夠確定爲了很好地內填補UILabel的這串正確的字體大小?

是否有一種基於屏幕矩形尺寸計算字體大小的數學方法?

例如:

UILabel *aLabel = [[UIlabel alloc] initwithFrame(CGRect){{0, 0}, 160, 240}]; 
aLabel.font = [UIFont fontWithName:@"Courier New" size:<???>]; //(font unit in points) 

NSMutableString *aString = [[NSMutableString alloc] init]; 

//The following tries to fit the character one by one within the label rect based on 
//the width and height of the UILabel by appending String 
int index = 0; 
for(int x = 0; x < 240; x+=<???>) //height of label (pixel unit) 
{ 
    for(int y = 0; y < 160; y+=<???>) //width of label (pixel unit) 
    { 
     [aString appendWithString:[paragraphArray objectAtIndex:index]]; 
     index++; 
    } 
    [aString appendWithString:@\n"]; //line break 
} 
aLabel.text = aString; 

我如何能夠確定的值,其中???是(即for循環的字體大小和像素大小)?

如果這不是執行此類任務的最佳方式,請給我建議任何其他信息。

回答

1
+(void)resizeFontForLabel:(UILabel*)aLabel{ 

    // use font from provided label so we don't lose color, style, etc 
    UIFont *font = aLabel.font; 

    float lblWidth = aLabel.frame.size.width; 
    float lblHeight = aLabel.frame.size.height; 

    CGFloat fontSize = [font pointSize]; 
    UIFont *newFont = font; 
    TRC_DBG(@"%@", aLabel.text); 
    CGFloat height = [aLabel.text sizeWithFont:font constrainedToSize:CGSizeMake(lblWidth,MAXFLOAT) lineBreakMode:aLabel.lineBreakMode].height; 

    TRC_DBG(@"Label Height %f Constraint height %f", lblHeight, height); 
    //Reduce font size while too large, break if no height (empty string) 
    while (height > lblHeight && height != 0) { 
     fontSize--; 
     newFont = [UIFont fontWithName:font.fontName size:fontSize]; 
     height = [aLabel.text sizeWithFont:newFont constrainedToSize:CGSizeMake(lblWidth,MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping].height; 
     TRC_DBG(@"Constrained Height %f", height); 
    }; 


    TRC_DBG(@"Font size before adjustment %f", aLabel.font.pointSize); 
    // Set the UILabel's font to the newly adjusted font. 
    aLabel.font = newFont; 
    TRC_DBG(@"Adjust to font size of %f", newFont.pointSize); 
    [aLabel setNeedsLayout]; 
} 
0

在故事板上單擊調整以適應並選擇最小尺寸。

相關問題