How to Get Width/Size/Length of UIString in a Specific Font

If you’ve ever been frustrated trying to find a way to compute the height of a string that wraps you will know my pain. Recently, I discovered that UIKit has made some addition to the NSString class that adds pure magic to the string type. If you lookup the NSString class in the documentation then you will never find out about these messages. For full details check out the NSString UIKit Additions Reference.

Here are just some of the messages that have made my life a little easier …

1
2
3
4
5
6
7
8
9
UIFont *myFont = [UIFont boldSystemFontOfSize:15.0];
// Get the width of a string ...
CGSize size = [@"Some string here!" sizeWithFont:myFont];
 
// Get the width of a string when wrapping within a particular width
NSString *loremIpsum = @"Lorem Ipsum Delores S...";
CGSize size = [loremIpsum sizeWithFont:myFont
                              forWidth:150.0 
		                lineBreakMode:UILineBreakModeWordWrap];
  1. Ah, this is a wonderful tip! I just started poking around with variable height table rows and was wondering “How do I know how big to make it?” Thanks a bunch!

  2. Great tips, it’s very useful. Thanks so much!

Comments are closed.