Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change font size to fit a UITextView

Tags:

ios

uitextview

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?

like image 258
user1941966 Avatar asked Feb 01 '14 00:02

user1941966


2 Answers

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
like image 135
Pwner Avatar answered Oct 23 '22 18:10

Pwner


this work fine in Swift 5 :

  func resizeFont(_ textView: UITextView) {
    if (textView.text.isEmpty || textView.bounds.size.equalTo(CGSize.zero)) {
              return;
          }

          let textViewSize = textView.frame.size;
          let fixedWidth = textViewSize.width;
    let expectSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat(MAXFLOAT)));

          var expectFont = textView.font;
          if (expectSize.height > textViewSize.height) {
            while (textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat(MAXFLOAT))).height > textViewSize.height) {
              expectFont = textView.font!.withSize(textView.font!.pointSize - 1)
                  textView.font = expectFont
              }
          }
          else {
            while (textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat(MAXFLOAT))).height < textViewSize.height) {
                  expectFont = textView.font;
                textView.font = textView.font!.withSize(textView.font!.pointSize + 1)
              }
              textView.font = expectFont;
          }

  }
like image 34
Ali Tavakoli Avatar answered Oct 23 '22 16:10

Ali Tavakoli