I am having the hardest time figuring out how to get the size, specifically the height, of a UILabel
containing specified text and using a specified font. Basically, I want a method that returns the height for a given string and font.
This is what I have so far:
+ (CGFloat)heightForString:(NSString *)string withFontSize:(CGFloat)size
{
NSDictionary *attributes = @{NSFontAttributeName : [UIFont systemFontOfSize:size]};
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:string
attributes:attributes];
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGRect paragraphRect =
[attributedText boundingRectWithSize:CGSizeMake(screenWidth, CGFLOAT_MAX)
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
context:nil];
return paragraphRect.size.height;
}
This returns a height that is about half the size it should be. I know this question has been asked a million times, but none of the solutions work fully.