sizeWithFont returns wrong heigth value

Hi! I've a little problem. I need a multiline text with a dynamic content, so i have to set a content of a UITextView via code. The problem is that the heigth returned by sizeWithFont:constrainedToSize:lineBreakMode: is not perfetc at all, is often smaller a little bit. Let see an example:


NSString *string1 = @"Hi to all!I've this question for you, and i hope you can help me";
CGSize maxSize = CGSizeMake(320.0, 1000.0);
UIFont *font = [UIFont fontWithName:@"Helvetica-Bold" size:20.0];
CGSize textSize = [[string1 sizeWithFont:font constrainedToSize:maxSize lineBreakMode:UILineBreakModeWordWrap];
NSLog(@"Frame at indexPath %d: heigth %f width %f", indexPath, textSize.width, textSize.width);
CGRect textViewFrame = CGRectMake(0.0, 0.0, textSize.width, textSize.height);
UITextView *aTextView = [[UITextView alloc] initWithFrame:textViewFrame];
aTextView.text = string1;
aTextView.font = [UIFont fontWithName:@"Helvetica-Bold" size:20.0];
aTextView.userInteractionEnabled = NO;

Then, string1 appears, but not at all. It seems that the aTextView is too short to contain all the words. Where's the problem?

MacBook Pro 2,4 Ghz 15,4", Mac OS X (10.5.3)

Posted on Jan 19, 2009 4:27 AM

Reply
1 reply

Jan 19, 2009 8:57 AM in response to McKracken

The problem you're having is UITextView may use margins, 22pt line spacing on your 20pt font, etc. There are a few variables beyond height and weight, so measuring the font height of the string, even when asking Quartz to measure it wrapped, won't yield the same result.

I think what you're trying to do is tell UITextView to be 320 pixels tall and then whatever height it likes. Since UITextView is a scrollable view, sizeToFit will allow for 0 by 0 which isn't too helpful. However, all UITextView does is wrap UILabel, so you can just go to UILabel directly. UILabel has a method textRectForBounds: that will tell you how much space your text will take.

Here is your example written using UILabel:

-----

NSString *string1 = @"Hi to all!I've this question for you, and i hope you can help me";
CGRect textSize = CGRectMake(0.0, 0.0, 320.0, FLT_MAX);
UIFont *font = \[UIFont fontWithName:@"Helvetica-Bold" size:20.0\];
UILabel *label = \[\[UILabel alloc\] init\];
label.lineBreakMode = UILineBreakModeWordWrap;
// Zero means infinite in this case
label.numberOfLines = 0;
label.font = font;
label.text = string1;
label.frame = \[label textRectForBounds:textSize limitedToNumberOfLines:0\];
NSLog(@"Frame at width %f height %f", label.frame.size.width, label.frame.size.height);

-----

Hope that helps,
Luke Chastain

Fixed Wiki markup by Luke Chastain

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

sizeWithFont returns wrong heigth value

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.