2011-11-07 57 views
0

使用IOS 4,我想通過編程方式瞭解給定的文本是否適合某個UILabel,我可以在不進行復雜計算的情況下獲取該信息嗎?如果不是什麼是最基本的方法來計算呢?iPhone:我如何理解一個文本是否適合標籤

+0

的可能重複的[如何計算特定字體的文本字符串的寬度和字體大小?](http://stackoverflow.com/questions/1324379/how-to-calculate-the-width-of-a-text-string-of-a-specific-font-and-font-size) – jrturton

回答

6

NSString方法sizeWithFont:contrainedToSize:lineBreakMode:可以提供幫助。它會給你CGSize與字符串的計算大小。只需將其與您的UILabel.frame.size進行比較即可。

8

您可以撥打NSString致電- (CGSize)sizeWithFont:(UIFont *)font

1

來確定與任何字體任何拉布勒的高度可以使用此功能

+(浮點)calculateHeightOfTextFromWidth:(的NSString *)文本:(UIFont *)withFont:(浮點)寬度:(UILineBreakMode) lineBreakMode;

+(float) calculateHeightOfTextFromWidth:(NSString*) text: (UIFont*)withFont: (float)width:(UILineBreakMode)lineBreakMode 
{ 
if (([text length]>0)) 
{ 
    CGSize suggestedSize = [text sizeWithFont:withFont constrainedToSize:CGSizeMake(width, FLT_MAX) lineBreakMode:lineBreakMode]; 
    return suggestedSize.height; 
} 
return 18; 
} 

這是一個例子來理解這種功能的工作

if (![isRateABusinessController length]) { 

    companyNameLabel.text = [NSString stringWithFormat:@"%@",[allDetails objectForKey:@"CNAME"]]; 

    NSString *cAdd = [NSString stringWithFormat:@"%@",[allDetails objectForKey:@"CADD"]]; 

    float height = [ConfirmationViewController calculateHeightOfTextFromWidth:cAdd :[UIFont fontWithName:@"Arial" size:14] :170 :UILineBreakModeWordWrap]; 

    addressLabel.text = [NSString stringWithFormat:@"%@",cAdd]; 

    if (height > 30) { 
     CGRect rect = CGRectMake(addressLabel.frame.origin.x , addressLabel.frame.origin.y, addressLabel.frame.size.width, addressLabel.frame.size.height+12.0); 
     addressLabel.frame = rect; 
    } 
} 
else 
{ 
    companyNameLabel.text = [NSString stringWithFormat:@"%@",[Utility selectedCompanyName]]; 

    NSString *cAdd = [NSString stringWithFormat:@"%@",[Utility selectedCompanyFullAddress]]; 
    // NSString *star  = [NSString stringWithFormat:@"Rating: %@",ratingName]; 

    float height = [ConfirmationViewController calculateHeightOfTextFromWidth:cAdd :[UIFont fontWithName:@"Arial" size:14] :170 :UILineBreakModeWordWrap]; 

    addressLabel.text = [NSString stringWithFormat:@"%@",cAdd]; 

    if (height > 30) { 
     CGRect rect = CGRectMake(addressLabel.frame.origin.x , addressLabel.frame.origin.y, addressLabel.frame.size.width, addressLabel.frame.size.height+12.0); 

     addressLabel.frame = rect; 
    } 
} 

}

相關問題