Fitted Labels

A recent problem required me to find bounding boxes for text on the iPhone. While this problem is neither typical nor particularly hard, I did spend some time digging though the documentation until I found an approach that I was happy with. Therefore, I thought I’d share what I found. (The short version is that the sizeToFit method of UILabel does the trick.)

Specifics

“Bounding boxes for text” could mean a lot of things. Here’s what I wanted, specifically:

  • Given a specified maximum width …
  • And a font …
  • And some text …
  • Fit the text into the smallest UILabel possible …
  • (Where “smallest” means “shortest, then narrowest”)
  • While respecting newlines …
  • And breaking lines only at words …
  • Unless a really long word forced you to do otherwise …
  • Oh, and never truncate the text vertically …
  • Return the size of the resulting UILabel

Implementation

Fortunately, this is one of those problems in which the answer is simpler than then question. The following code will produce appropriate UILabels:

- (UILabel*)makeLabelWithWidth:(CGFloat)w font:(UIFont*)f text:(NSString*)s
{
	// Create label
	UILabel* label = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, w, 1)] autorelease];
	
	// Configure (for multi-line word-wrapping)
	label.font = f;
	label.numberOfLines = 0;
	label.lineBreakMode = UILineBreakModeWordWrap;
	
	// Set, size, and return
	label.text = s;
	[label sizeToFit];
	return label;
}

The key, as you can see, is the sizeToFit call, which, in the case of UILabels, just Does The Right Thing. Also, please note that the initial height of the UILabel is basically irrelevant.

Share and Enjoy:
  • Twitter
  • Facebook
  • Digg
  • Reddit
  • HackerNews
  • del.icio.us
  • Google Bookmarks
  • Slashdot
This entry was posted in iPhone. Bookmark the permalink.

Comments are closed.