Resize font size to fill UITextView?

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

    Hope that's clearer:

    extension UITextView {
        @objc public func fitText() {
            fitText(into: frame.size)
        }
    
        @objc public func fitText(into originalSize: CGSize) {
            let originalWidth = originalSize.width
            let expectedSize = sizeThatFits(CGSize(width: originalWidth, height: CGFloat(MAXFLOAT)))
    
            if expectedSize.height > originalSize.height {
                while let font = self.font, sizeThatFits(CGSize(width: originalWidth, height: CGFloat(MAXFLOAT))).height > originalSize.height {
                    self.font = font.withSize(font.pointSize - 1)
                }
            } else {
                var previousFont = self.font
                while let font = self.font, sizeThatFits(CGSize(width: originalWidth, height: CGFloat(MAXFLOAT))).height < originalSize.height {
                    previousFont = font
                    self.font = font.withSize(font.pointSize + 1)
                }
                self.font = previousFont
            }
        }
    }
    

提交回复
热议问题