Saturday, April 20, 2013

iOS Tip - Obtaining the height of a string to be displayed based on width, font and font size

A lot of times, you need to display a string of text on your iOS app UI. For example, you may need to create an image to contain a string of text (like displaying a bubble containing a SMS message) and hence need to calculate the height taken up by the text based on the width that you are using to display the text. The following code snippet calculates the height of text based on the width specified, as well as the standard system font and specified font size:

//---calculate the height needed to display the text
// based on given width, font, and font size---
-(CGFloat) textHeight:(NSString *) text withWidth:(int) viewWidth andSize:(int) fontSize{
CGSize maximumTextSize = CGSizeMake(viewWidth,9999);
CGSize expectedTextSize = [text sizeWithFont:[UIFont systemFontOfSize: fontSize]
return expectedTextSize.height;

To use the textHeight:withWidth:andSize: method, simply call it like this:

    float textHeight = [self textHeight:@"The quick brown fox jumps over the lazy dog" 

Have fun!

No comments: