Resize font size to fill UITextView?

后端 未结 15 932
春和景丽
春和景丽 2020-12-01 07:03

How would I set the font size of text in a UITextView such that it fills the entire UITextView? I\'d like the user to type in their text, then have the text fill the entire

相关标签:
15条回答
  • 2020-12-01 07:36

    In viewDidLoad:

    textView.textContainer.lineFragmentPadding = 0;
    textView.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0);
    

    You need to add UITextViewDelegate:

    - (void)updateTextFont:(UITextView *)textView {
    
        CGSize textViewSize = textView.frame.size;
        CGSize sizeOfText = [textView.text sizeWithAttributes:@{NSFontAttributeName: textView.font}];
    
        CGFloat fontOfWidth = floorf(textView.font.pointSize / sizeOfText.height * textViewSize.height);
        CGFloat fontOfHeight = floorf(textView.font.pointSize / sizeOfText.width * textViewSize.width);
    
        textView.font = [textView.font fontWithSize:MIN(fontOfHeight, fontOfWidth)];
    }
    
    0 讨论(0)
  • 2020-12-01 07:40

    Here is my sample code. Basically, I check the expect size to know if font size need to increase or decrease. You need to add UITextViewDelegate to your class to make sure it workings

    - (void)updateTextFont:(UITextView *)textView
    {
        // Only run if has text, otherwise it will make infinity loop
        if (textView.text.length == 0 || CGSizeEqualToSize(textView.bounds.size, CGSizeZero)) return;
    
        /*
         - Update textView font size
         If expectHeight > textViewHeight => descrease font size n point until it reach textViewHeight
         If expectHeight < textViewHeight => inscrease font size n point until it reach textViewHeight
         */
        CGSize textViewSize = textView.frame.size;
        CGFloat fixedWidth = textViewSize.width;
        CGSize expectSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
    
        UIFont *expectFont = textView.font;
        if (expectSize.height > textViewSize.height) {
            while ([textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)].height > textViewSize.height) {
                expectFont = [textView.font fontWithSize:(textView.font.pointSize-1)];
                textView.font = expectFont;
            }
        } else {
            while ([textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)].height < textViewSize.height) {
                expectFont = textView.font;
                textView.font = [textView.font fontWithSize:(textView.font.pointSize+1)];
            }
            textView.font = expectFont;
        }
    }
    
    0 讨论(0)
  • 2020-12-01 07:48

    U can easily do this by using

    • self.textview.font =

    self.textview.font = UIFont(name: self.textview.font!.fontName,
    size: self.textview.frame.size.height / 10)!

    divide textview.frame.size.height upon some constant based on your requirement..

    0 讨论(0)
提交回复
热议问题