views:

595

answers:

5

Can anybody recommend a good method for determining the Rect of some wrapped text on an iPhone? I've tried all the built-in methods for NSString in the 2.1 SDK to no avail. The size methods never return sizes that allow me to completely fit wrapped text in my custom view.

I'm drawing some user customizable text that should always be as big as possible within the limits of my custom view. If I can determine the rect needed to completely enclose wrapped text for a given max width and font size, I can raise or lower the font size until the text is just big enough to completely fill the custom view without being clipped.

Any help is much appreciated!

+3  A: 

NSString's sizeWithFont:constrainedToSize: method might be useful:

CGSize sizeForText = [theText sizeWithFont:theFont constrainedToSize:CGSizeMake(myMaxWidth, 9999)];

You say you've tried all the size methods, but based on your description, it sounds like what you're looking for.

Mike McMaster
A: 

Since you know your view size, call NSString's sizeWithFont:forWidth:lineBreakMode:, starting with your minimum font size, the width of your view, and UILineBreakModeWordWrap. Then increase the font size until the returned size is as tall as your view.

If you want to set a maximum font size, you could also implement this as a binary search, rather than stepping up the font size.

benzado
A: 

@Mike McMaster: I did try using that method before only giving it the actual constraints of my view rather than giving it a huge number for the max height. Using a large number for the max height worked like a charm!

@benzado: That method never seemed to give me a height which incorporated the number of lines involved after wrapping. It seemed like it was only giving me back the height for a single line. Maybe by tweaking the values I was passing the method further I might've had results closer to what I got using the method recommended by Mike.

Thanks tons for your help guys!

A: 

Hi, the above does not work for me whatever I try. It always returns a height of 55 for my font even though the entire text does not fit on one line and I use UILineBreakModeWordWrap. Any ideas what could cause this?

Best Regards,

André

A: 

I found that whenever you set your UITextView's text property, it updates its contentSize property. That makes it very easy to resize the text view's frame for displaying within a scroll view, etc.

spstanley