0

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?

Spring
  • 11,333
  • 29
  • 116
  • 185
  • possible duplicate of [How to calculate the width of a text string of a specific font and font-size?](http://stackoverflow.com/questions/1324379/how-to-calculate-the-width-of-a-text-string-of-a-specific-font-and-font-size) – jrturton Nov 07 '11 at 13:24

3 Answers3

8

You can call - (CGSize)sizeWithFont:(UIFont *)font on NSString.

tobiasbayer
  • 10,269
  • 4
  • 46
  • 64
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