Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
431 views
in Technique[技术] by (71.8m points)

iphone - UILabel's sizeToFit/sizeThatFits ignore the numberoflines property

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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... :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...