Resize font size to fill UITextView?

后端 未结 15 941
春和景丽
春和景丽 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 conversion of dementiazz's and Matt Frear's answer to Swift 5. Put this function into viewDidLayoutSubviews, referencing the UITextView's who's font you want to dynamically resize.

    func updateTextFont(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;
        }
    }
    

提交回复
热议问题