Resize font size to fill UITextView?

后端 未结 15 1021
春和景丽
春和景丽 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:27

    Similar approach to Arie Litovsky's answer but without sub-classing (or use of a category) and not using contentSize which didn't return the correct height of the rendered text for me. Tested on iOS 7:

    while (((CGSize) [_textView sizeThatFits:_textView.frame.size]).height > _textView.frame.size.height) {
        _textView.font = [_textView.font fontWithSize:_textView.font.pointSize-1];
    }
    

    The approach is to keep reducing the font size until the text just fits inside the frame of the text view.

    If you were going to use this in production you would still need to:

    • Handle the case where even with the smallest-possible font size the text still won't fit.
    • Use a similar approach to increase the font size if you would also like to scale text up to fit the frame.

提交回复
热议问题