Skip to content

Instantly share code, notes, and snippets.

@DanielCardonaRojas
Last active June 4, 2020 17:43
Show Gist options
  • Save DanielCardonaRojas/3f3ef06f3658ae7f2ecd442735e739fc to your computer and use it in GitHub Desktop.
Save DanielCardonaRojas/3f3ef06f3658ae7f2ecd442735e739fc to your computer and use it in GitHub Desktop.
Expanding TextView
extension UITextView {
func makeSelfSizing() -> [NSKeyValueObservation] {
self.isScrollEnabled = false
NotificationCenter.default.addObserver(self, selector: #selector(didChangeTextViewContent), name: .UITextViewTextDidChange, object: self)
return [
observe(\UITextView.text, changeHandler: { this, change in
self.didChangeTextViewContent()
}),
observe(\UITextView.attributedText, changeHandler: { this, change in
self.didChangeTextViewContent()
})]
}
@objc func didChangeTextViewContent() {
if !self.isScrollEnabled {
let unboundedSize = CGSize(width: self.frame.width, height: .infinity)
let estimatedSize = self.sizeThatFits(unboundedSize)
self.frame.size = estimatedSize
self.constraints.forEach { constraint in
if constraint.firstAttribute == .height {
constraint.constant = estimatedSize.height
}
}
setNeedsUpdateConstraints()
setNeedsLayout()
superview?.setNeedsUpdateConstraints()
superview?.setNeedsLayout()
}
}
}
@DanielCardonaRojas
Copy link
Author

Note:

  • A height constraint must be set to the textview
  • When used in a table view cell, calling beginUpdates and endUpdates on the tableView is required.

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