Last active
June 4, 2020 17:43
-
-
Save DanielCardonaRojas/3f3ef06f3658ae7f2ecd442735e739fc to your computer and use it in GitHub Desktop.
Expanding TextView
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note: