Using IOS 4, I want to understand programatically if a given text is fitting to a certain UILabel or not, can i get that information without doing complex calculations? if not what is the most basic approach for calculating that?
Asked
Active
Viewed 716 times
3 Answers
6
NSString method sizeWithFont:contrainedToSize:lineBreakMode: could help. It will give you CGSize with calculated size of string. Just compare this with your UILabel.frame.size.

Artur Ozierański
- 1,177
- 7
- 18
1
To Determine the height of any lable with any font you can use this function
+(float) calculateHeightOfTextFromWidth:(NSString*) text: (UIFont*)withFont: (float)width: (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;
}
This is one example to understand the working of this function
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;
}
}
}

vijay gupta
- 242
- 1
- 12