As you can see in this image
the UITextView
changes it\'s height according to the text length, I want to make it adjust it\'s height according to the te
If your textView
is allowed to grow as tall as the content, then
textView.isScrollEnabled = false
should just work with autolayout.
If you want to remain the textView
to be scrollable, you need to add an optional height constraint,
internal lazy var textViewHeightConstraint: NSLayoutConstraint = {
let constraint = self.textView.heightAnchor.constraint(equalToConstant: 0)
constraint.priority = .defaultHigh
return constraint
}()
public override func layoutSubviews() {
super.layoutSubviews()
// Assuming there is width constraint setup on the textView.
let targetSize = CGSize(width: textView.frame.width, height: CGFloat(MAXFLOAT))
textViewHeightConstraint.constant = textView.sizeThatFits(targetSize).height
}
The reason to override layoutSubviews()
is to make sure the textView is laid out properly horizontally so we can rely on the width to calculate the height.
Since the height constraint is set to a lower priority, if it runs out space vertically the actual height of the textView
will be less than the contentSize
. And the textView will be scrollable.