Reputation: 2146
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.
Upvotes: 0
Views: 308
Reputation: 2146
I have decided to simply create a dummy label, set it's text property and set numberOfLines
to 0 and say [label sizeToFit]
that will allow you to get the frame of the label, which includes the height. It's not an ideal way, but it works.
Apparently in iOS 8 there will be self sizing table view cells! Cannot wait!
Upvotes: 0
Reputation: 11039
Use this category to calculate height of text with given font and max width, which is used in in SOMessaging
Basically I made it as replacement of sizeWithFont:constrainedToSize:lineBreakMode
method of iOS6
Upvotes: 1