Measuring text with sizeWithFont returns height one line too short
Posted
by Mac
on Stack Overflow
See other posts from Stack Overflow
or by Mac
Published on 2010-03-29T00:36:10Z
Indexed on
2010/03/29
0:43 UTC
Read the original article
Hit count: 650
In an iPhone app I'm working on, I'm trying to get a UILabel to dynamically adjust its size based on its content. To do so, I'm using NSString's sizeWithFont:constrainedToSize
method to measure the height of the text when constrained to a given width, and then set the UILabel to that width and the returned height. The problem however, is that roughly half the time sizeWithFont
is returning a height for the text that is one line too short. This happens mostly with long strings (a couple of hundred characters), but also very occasionally with shorter strings (less than one hundred).
For reference, my code looks like the following (textLabel
is the UILabel in question and is a member variable, TEXT_WIDTH
is the desired label width):
- (void) setLabelText:(NSString*) text
{
CGSize bounds = CGSizeMake(TEXT_WIDTH, CGFLOAT_MAX);
int textHeight = [text sizeWithFont:textLabel constrainedToSize:bounds
lineBreakMode:UILineBreakModeWordWrap].height;
CGRect newFrame = CGRectMake(0, 0, TEXT_WIDTH, textHeight);
[textLabel setFrame:newFrame];
}
Just to be clear, I don't believe the issue is with the UILabel, as I've manually inspected the value being returned by sizeWithFont
and can confirm that the number being returned for the height is too small on the occasions when the label is also too small.
© Stack Overflow or respective owner