Resize font size to fill UITextView?

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

    Here is a solution for Swift 4 (based on Arie Litovsky answer), you can put this code into textViewDidChange(_ textView: UITextView) delegate method :

    Scaling down the font :

        while (textView.contentSize.height > textView.frame.size.height) {
            guard let fontName = textView.font?.fontName, let fontSize = textView.font?.pointSize else {return}
            if fontSize < 12 {
                return
            }
            textView.font = UIFont(name: fontName, size: fontSize - 1)
            textView.layoutIfNeeded()
        }
    

    And scaling up the font:

            while (textView.contentSize.height < textView.frame.size.height) {
            guard let fontName = textView.font?.fontName, let fontSize = textView.font?.pointSize else {return}
            if fontSize > 15 {
                return
            }
            textView.font = UIFont(name: fontName, size: fontSize + 1)
            textView.layoutIfNeeded()
        }
    

    You can change the fontSize < 12 and fontSize > 15 to fit your needs in minimum and maximum font size.

提交回复
热议问题