Change font size to fit a UITextView

ios, uitextview

Solution

Only `UITextField` (the single line input) has `adjustsFontSizeToFitWidth` and `minimumFontSize` properties. With `UITextView`, you'll have to program that yourself.

static const CGFloat MAX_FONT_SIZE = 16.0;
static const CGFloat MIN_FONT_SIZE = 4.0;

@interface MyViewController ()

// I haven't dealt with Storyboard / Interface builder in years,
// so this is my guess on how you link the GUI to code
@property(nonatomic, strong) IBOutlet UITextView* textView;

- (void)textDidChange:(UITextView*)textView;

@end

@implementation MyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.textView addTarget:self action:@selector(textDidChange:) forControlEvents:UIControlEventEditingChanged];
    self.textView.font = [UIFont systemFontOfSize:MAX_FONT_SIZE];
}

- (void)textDidChange:(UITextView*)textView
{
    // You need to adjust this sizing algorithm to your needs.
    // The following is oversimplistic.
    self.textView.font = [UIFont systemFontOfSize:MAX(
        MAX_FONT_SIZE - textView.text.length, 
        MIN_FONT_SIZE
    )];
}

@end

Problem

I have a UITextView set up in Storyboard. It is set at a defined size. I want to be able to change the size of the font based on how much text there is. The text view cannot be edited by the user and it only has to update once. Any idea how to do this?

Original source