Just starting with a new language and new framework you always run into problems that you never thought would be a problem. I’ve encountered the problem of finding out the height/width of text when drawn on screen when I was working with a Java applet. Now that I’m working on my GPS and internet aware iPhone app, together with my good friend since preschool and now colleague Hampus at Avantime, we consume a web service which serves us information. Of course, when fetching information from others you seldom know how much information they will send you. Working with a competent device like the iPhone I was surprised how much time I spent searching for the proper way to do it. When looking at the API reference I thought that setting the number of lines to 0 would do the trick, which it doesn’t. I tried everything I could find in the API reference but nothing would produce the multiline label I wanted. In our application we present the information in a nice UITableView, just like the Facebook application does (Facebook 2.0 application is awesome btw!). Eventually I found the method sizeWithFont in NSString which does exactly what I want. Here’s my static method that I will return the appropriate height for a label with a given width, font and line break mode:

+(float) calculateHeightOfTextFromWidth:(NSString*) text: (UIFont*)withFont: (float)width :(UILineBreakMode)lineBreakMode
{
[text retain];
[withFont retain];
CGSize suggestedSize = [text sizeWithFont:withFont constrainedToSize:CGSizeMake(width, FLT_MAX) lineBreakMode:lineBreakMode];
 
[text release];
[withFont release];
 
return suggestedSize.height;
}

What this method does is return the appropriate size of a drawn on the screen, however it doesn’t return a wider or taller size than constrain it to. Therefore I give it the maximum size of a float (which is a constant) for height and it will return the appropriate size.

Making the entire scrollable view with a dynamic UITableView with dynamic height on different cells was quite a challenge. I’ll share some thoughts and our solution for that in the future.

Related posts