41

Problem: Determine the size (number of lines) a UILabel needs, assuming the width is 300 px. The string is longer, so I set the lineBreakMode to UILineBreakModeWordWrap and invoked sizeThatFits to try to determine the size. But it gives a width of 457 px in a single line, rather than the expected 300px in two lines.

Please see:

CGSize available = CGSizeMake(300, INFINITY);
UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 400)] autorelease];
label.text = title;
label.lineBreakMode = UILineBreakModeWordWrap;
label.font = [UIFont fontWithName:kBoldFont size:kTitleFontSize];
label.numberOfLines = 3;
CGSize sizedtoFit = [label sizeThatFits:available];

But I find that the sizedtoFit variable has a width of 457 pixels and a height of 22 px, and the UI displays a single line with clipped text. I expect a width of 300 pixels, and a height of 44 px for two lines.

The UILabel doc for numberoflines says:

When the receiver is resized using the sizeToFit method, resizing takes into account the value stored in this property. For example, if this property is set to 3, the sizeToFit method resizes the receiver so that it is big enough to display three lines of text.

I tried various combinations of:

  1. Passing CGRectZero to the init function, passing 300x400 or 300 x infinity.
  2. Setting the frame after creation rather than passing it to the init function.
  3. Invoking [sizeToFit] and hoping it calculates the height assuming present width, but it doesn't.
  4. Calling sizeToFit and then calling sizeThatFits`.
  5. Invoking layoutIfNeeded.

None of them works. What am I doing wrong, or is this is bad bug where the documentation and the framework implementation don't agree? Thanks.

3
  • According to the doc, I believe it is a bug and I just reported it.
    – an0
    Feb 7, 2012 at 15:14
  • 3
    This seems to be fixed in iOS6 – [ sizeToFit] now takes numberOfLines into account. Oct 25, 2012 at 11:29
  • @Pavel is right, just upgraded from 5.1 to 6.0 and magically sizeToFit returns the correct size (with increased height).
    – Kirk Woll
    Oct 29, 2012 at 21:54

6 Answers 6

29

I had the same problem, size that fits simply ignores the size... /: I ended up using:

CGRect textSize = [UILabel textRectForBounds:CGRectMake(0, 0, 300, CGFLOAT_MAX) 
                      limitedToNumberOfLines:3];

Works like a charm... :)

The documentation says you shouldn't call it directly, but i've been using it for a while, with approved submitted apps, and everything is just awesome... :)

6
  • 2
    I wouldn't be comfortable with doing that except as a last resort :) Nov 14, 2011 at 2:10
  • care to elaborate on that @KartickVaddadi ? :)
    – Alex Zak
    Nov 28, 2011 at 1:21
  • 8
    Well, I don't want to do things the documentation says you shouldn't, except as a last resort. Nov 29, 2011 at 1:51
  • 2
    Does this assume that you're using the default font? Dec 3, 2012 at 21:29
  • 3
    The current documentation seems fine with using the instance method CGRect textSize = [label textRectForBounds:CGRectMake(0, 0, 300, CGFLOAT_MAX) limitedToNumberOfLines:3]. Note: this is not a class method as in @AlexZak's answer. Ref: developer.apple.com/library/ios/documentation/uikit/reference/…: Jul 7, 2014 at 16:00
7

Have you tried the sizeWithFont: constrainedToSize: lineBreakMode: method?

For example:

CGSize sizeToFit = [title sizeWithFont:label.font constrainedToSize:label.frame.size lineBreakMode:label.lineBreakMode];
3
  • 1
    That was my fallback option, but the question is: why is sizeThatFits not working as it should? I was just told that if I set the numberOfLines to 0 (unlimited), it works. Feb 20, 2011 at 6:42
  • This is no good if you want a maximum of three lines, like the question implied. Guess I need to calculate the height of three lines and pass it in to the sizeWithFont function then. Which sucks.
    – mxcl
    Apr 5, 2011 at 13:34
  • great answer. I found this the most useful for multiline labels. sizeWithFont is deprecated in iOS7, though. Have a look at my separate answer using boundingRectWithSize:
    – auco
    Oct 4, 2013 at 16:43
3

I found Ian L's answer best using -sizeWithFont:constrainedToSize:lineBreakMode:, unfortunately sizeWithFont: is deprecated under iOS7.

This is how sizeWithFont: works for a UILabel subclass in iOS7:

NSRange range = NSMakeRange(0, self.attributedText.length); 
sizeToFit = [self.text boundingRectWithSize:self.bounds.size
                                    options:NSStringDrawingUsesLineFragmentOrigin 
                                 attributes:[self.attributedText 
                          attributesAtIndex:0 effectiveRange:&range] context:nil].size;
1

This is all deprecated. Use boundingRectWithSize

0

I think you are getting unexpected results because you are not taking into consideration the UILabel's font. Try the following:

UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 400)] autorelease];
label.text = title;
label.lineBreakMode = UILineBreakModeWordWrap;
label.font = [UIFont fontWithName:kBoldFont size:kTitleFontSize];
label.numberOfLines = 0;

CGSize size = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(label.frame.size.width,FLT_MAX) lineBreakMode:UILineBreakModeWordWrap ];
label.frame = CGRectMake(label.frame.origin.x,label.frame.origin.y,label.frame.size.width,size.height);
2
  • This solution doesn't limit the number of lines Apr 11, 2011 at 21:44
  • In addition to not limiting the number of lines, it uses the NSString sizing method, which will ignore a ton of the additional capabilities of UILabel
    – pottedmeat
    Feb 8, 2012 at 20:58
0

There is no solution for ios5 for sizeToFit. You may use other solutions like sizeWithFont etc. In ios6, the issue is fixed. However, I have this workaround for my solutions:

int lineCount = myLabel.numberOfLines;
myLabel.numberOfLines = 0;
[myLabel sizeToFit];
myLabel.numberOfLines = lineCount;

And it works. Beware that for my situation, width of my label is fixed and I only need sizeToFit for adjusting height.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.