I have a TextView that has a constraint of min height of 33. The scroll is disabled from the storyboard. The TextView should increase in height based on the content until it
Create a class that inherits from UITextView and add the following into the class:
class CustomTextView: UITextView, UITextViewDelegate {
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
delegate = self
}
var maxHeight: CGFloat = 200
override var intrinsicContentSize: CGSize {
var size = super.intrinsicContentSize
if size.height > maxHeight {
size.height = maxHeight
isScrollEnabled = true
} else {
isScrollEnabled = false
}
return size
}
override var text: String! {
didSet {
invalidateIntrinsicContentSize()
}
}
func textViewDidChange(_ textView: UITextView) {
invalidateIntrinsicContentSize()
}
}
Note: - You can initialize maxHeight to infinity and set maxHeight after creating the CustomTextView. This class can be reused anywhere it is needed in the app, and the max height can be modified for different scenarios.