Home > Mobile, Programming > Size-to-Fit Text in UITextView (iPhone)

Size-to-Fit Text in UITextView (iPhone)

April 27th, 2011

The UITextView is a very useful view. You’re able to show and interact with large amounts of text. However, I recently found the need to size the UITextView in Interface Builder to fit nicely in a pre-layed out interface. Well, low-and-behold the client I was working for started sending large amounts of text that was to be displayed here. We didn’t want scrolling but needed to display all the text. So, we needed to resize the text until it would fit and all would be displayed. Below is a very simple way of resizing the text in the UITextView to fit within its current bounds.

At some point define the max size you want the font to be. I typically put this in my .h file

#define kDefaultFontSize 24.0

Then in your .m file where you add the text to the UITextView you would place something like:

myTextView.text = @"Some long string that will be in the UITextView";
myTextView.font = [UIFont systemFontOfSize:kDefaultFontSize];

//setup text resizing check here
if (myTextView.contentSize.height > myTextView.frame.size.height) {
    int fontIncrement = 1;
    while (myTextView.contentSize.height > myTextView.frame.size.height) {
        myTextView.font = [UIFont systemFontOfSize:kDefaultFontSize-fontIncrement];

Hope this helps! Enjoy!

Comments are closed.