Calculate size of UILabel with different font types

111 views Asked by At

I'm building an app with minimum version of iOS 7. In the method where i draw my cells, i have this code to draw a UILabel with different UIFonts types.

//Get Strings
NSString* author = [self getUserCreatedVideo:notf];
NSString* caption = [NSString stringWithFormat:@"\"%@\"", [notf objectForKey:@"title"]];
NSString* challenge = @"challenged you to reply to";
NSString* timeToReply = @"24h to reply";
NSString* myString = [NSString stringWithFormat:@"%@ %@ %@ %@", author, challenge, caption, timeToReply];

NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:myString];
UIColor* greenColor = [UIColor colorWithRed:102.0/255.0 green:204.0/255.0 blue:153.0/255.0 alpha:1];

//Author
[str addAttribute:NSForegroundColorAttributeName value:[UIColor darkGrayColor] range:NSMakeRange(0,author.length)];
[str addAttribute:NSFontAttributeName value: [UIFont fontWithName:@"Helvetica" size:17.0] range:NSMakeRange(0,author.length)];
//Challenge
[str addAttribute:NSForegroundColorAttributeName value:[UIColor lightGrayColor] range:NSMakeRange(author.length+1,challenge.length)];
[str addAttribute:NSFontAttributeName value: [UIFont fontWithName:@"Helvetica" size:13.0] range:NSMakeRange(author.length+1,challenge.length)];
//Caption
[str addAttribute:NSForegroundColorAttributeName value:[UIColor darkGrayColor] range:NSMakeRange(author.length+1+challenge.length+1,caption.length)];
[str addAttribute:NSFontAttributeName value: [UIFont fontWithName:@"Helvetica" size:14.0] range:NSMakeRange(author.length+1+challenge.length+1,caption.length)];
//Time To Reply
[str addAttribute:NSForegroundColorAttributeName value:greenColor range:NSMakeRange(author.length+1+challenge.length+1+caption.length+1,timeToReply.length)];
[str addAttribute:NSFontAttributeName value: [UIFont fontWithName:@"Helvetica" size:14.0] range:NSMakeRange(author.length+1+challenge.length+1+caption.length+1,4)];

cell.subtext.attributedText = str;

Now i want to calculate the UILabel text size, so that i can draw a UILabel 20px below cell.subtext. How can i achieve this?

1

There are 1 answers

1
Juraj Antas On BEST ANSWER

So basically you want to calculate height of text when you know text width.

CGRect rect = [str boundingRectWithSize:CGSizeMake(cellWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin context:nil];

Use resulting rect.size the way you want.