Skip to content

Instantly share code, notes, and snippets.

@joshavant
Created July 21, 2016 03:00
Show Gist options
  • Save joshavant/0540b463b877f0bdecefbc44848a4501 to your computer and use it in GitHub Desktop.
Save joshavant/0540b463b877f0bdecefbc44848a4501 to your computer and use it in GitHub Desktop.
UITextView Height Calculation
extension UITextView {
// Note: This will trigger a text rendering!
func calculateViewHeightWithCurrentWidth() -> CGFloat {
let textWidth = self.frame.width -
self.textContainerInset.left -
self.textContainerInset.right -
self.textContainer.lineFragmentPadding * 2.0 -
self.contentInset.left -
self.contentInset.right
let maxSize = CGSize(width: textWidth, height: CGFloat.max)
var calculatedSize = self.attributedText.boundingRectWithSize(maxSize,
options: [.UsesLineFragmentOrigin, .UsesFontLeading],
context: nil).size
calculatedSize.height += self.textContainerInset.top
calculatedSize.height += self.textContainerInset.bottom
return ceil(calculatedSize.height)
}
}
@SuperNova911
Copy link

Thanks god, you saved me 😭 😭 😭 😭 😭 😭 😭 😭 😭 😭 😭 😭 😭 😭 😭

@chrisladd
Copy link

I made a couple of changes for my own purposes, in case it's useful for anyone else:

  1. updated to fix renamed methods
  2. added ability to pass in your own width. For me, this made it easier to integrate into a sizeThatFits method
  3. if there is no text yet, measures with placeholder text so you get an accurate starting frame.

Thanks for getting this started!

extension UITextView {

    func neededHeightWithWidth(_ width: CGFloat) -> CGFloat {
        let textWidth = self.frame.width -
        self.textContainerInset.left -
        self.textContainerInset.right -
        self.textContainer.lineFragmentPadding * 2.0 -
        self.contentInset.left -
        self.contentInset.right
        
        let maxSize = CGSize(width: textWidth, height: CGFloat.greatestFiniteMagnitude)
        
        let attributedText: NSAttributedString
        if let text = self.attributedText, text.length > 0 {
            attributedText = text
        }
        else {
            attributedText = NSAttributedString(string: "XXX", attributes: typingAttributes)
        }
        
        var calculatedSize = attributedText.boundingRect(with: maxSize,
                                                              options: [.usesLineFragmentOrigin, .usesFontLeading],
                                                                      context: nil).size
        calculatedSize.height += self.textContainerInset.top
        calculatedSize.height += self.textContainerInset.bottom
        
        return ceil(calculatedSize.height)
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment