Note that there are some explanatory texts on larger screens.

plurals
  1. POUILabel's sizeToFit/sizeThatFits ignore the numberoflines property
    text
    copied!<p>Problem: Determine the size (number of lines) a <code>UILabel</code> needs, assuming the width is 300 px. The string is longer, so I set the <code>lineBreakMode</code> to <code>UILineBreakModeWordWrap</code> and invoked <code>sizeThatFits</code> 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.</p> <p>Please see:</p> <pre><code>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]; </code></pre> <p>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.</p> <p>The UILabel doc for numberoflines says:</p> <p>When the receiver is resized using the <code>sizeToFit</code> method, resizing takes into account the value stored in this property. For example, if this property is set to 3, the <code>sizeToFit</code> method resizes the receiver so that it is big enough to display three lines of text.</p> <p>I tried various combinations of:</p> <ol> <li>Passing <code>CGRectZero</code> to the init function, passing 300x400 or 300 x infinity.</li> <li>Setting the frame after creation rather than passing it to the <code>init</code> function.</li> <li>Invoking <code>[sizeToFit]</code> and hoping it calculates the height assuming present width, but it doesn't.</li> <li>Calling sizeToFit and then calling sizeThatFits`.</li> <li>Invoking <code>layoutIfNeeded</code>.</li> </ol> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload