简体   繁体   中英

Calculate size of UILabel with different font types

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM