iOS programming: calculate height of text area
EDIT: A friend on Twitter informed me that the better way to do this is:
[nameText sizeWithFont:font constrainedToSize:CGSizeMake(300.f, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];
The key being that you can create a CGSize object with MAXFLOAT as the height.
My iOS skills are certainly a work in progress.
While learning objective C I thought a good test project would be to give some love to my old friend Nerd Nearby.
Nerd nearby is pulling local info from several services such as instagram and foursquare. Since the data is unique to each user we have to dynamically size each section of each cell to accomodate different amounts of text.

In this example there are 2 lines of text but this will change with each item. This is trivially easy in HTML/CSS but it turns out that in iOS it’s tricky to do dynamic resizing because here are no built in functions to find out how tall your text should be given a fixed height.
My solution was to add a category that extended NSString. In objective C they make it really really easy to add methods to a class from any library. This is a little scary to me but for now I’m rolling with it. Here’s my code:
In NSString+NerdNearby.h:
@interface NSString (NerdNearby)
- (CGSize) multilineSizeWithFont:(UIFont *)font forWidth:(float)width lineBreakMode:(UILineBreakMode)lineBreakMode;
@end
And the gross bit, in NSString+NerdNearby.m:
@implementation NSString (NerdNearby)
- (CGSize) multilineSizeWithFont:(UIFont *)font forWidth:(float)width lineBreakMode:(UILineBreakMode)lineBreakMode
{
CGSize size = [self sizeWithFont:font];
CGSize oneLineSize = [self sizeWithFont:font forWidth:width lineBreakMode:lineBreakMode];
if (size.width > width) {
float area = size.width * size.height;
float newHeight = area/widthSize.width;
if ((int)ceil(newHeight) % (int)oneLineSize.height != 0 ) {
newHeight = (float) ((ceil)(newHeight/oneLineSize.height) * (int)oneLineSize.height);
}
size.height = newHeight;
}
size.width = width;
return size;
}
@end
This is certainly not perfect. For instance, it only checks if the first line break would be shorter than the width. I’m not really sure how to access how long the second line of text would be. For my purposes though, it’s good enough.