0

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.

tshepang
  • 12,111
  • 21
  • 91
  • 136
tentmaking
  • 2,076
  • 4
  • 30
  • 53
  • Try to use this solution-> http://stackoverflow.com/questions/446405/adjust-uilabel-height-depending-on-the-text I hope it help you. – LLIAJLbHOu Jun 21 '14 at 15:52
  • MobiDevCom that solution uses sizeWithFont...That method was deprecated in iOS7. Thanks though! – tentmaking Jun 21 '14 at 20:12
  • 1
    In the past I've simply created a dummy label, inserted the text, and then used the option (forget which one) to squeeze the label down to the minimum size that fits the text. Sometimes I create a single global label just for this temporary use. (The label does not need to be in a view anywhere.) – Hot Licks Jun 29 '14 at 21:46

2 Answers2

1

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

arturdev
  • 10,884
  • 2
  • 39
  • 67
0

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!

tentmaking
  • 2,076
  • 4
  • 30
  • 53