UITextView that expands to text using auto layout UITextView that expands to text using auto layout ios ios

UITextView that expands to text using auto layout


Summary: Disable scrolling of your text view, and don't constraint its height.

To do this programmatically, put the following code in viewDidLoad:

let textView = UITextView(frame: .zero, textContainer: nil)textView.backgroundColor = .yellow // visual debuggingtextView.isScrollEnabled = false   // causes expanding heightview.addSubview(textView)// Auto LayouttextView.translatesAutoresizingMaskIntoConstraints = falselet safeArea = view.safeAreaLayoutGuideNSLayoutConstraint.activate([    textView.topAnchor.constraint(equalTo: safeArea.topAnchor),    textView.leadingAnchor.constraint(equalTo: safeArea.leadingAnchor),    textView.trailingAnchor.constraint(equalTo: safeArea.trailingAnchor)])

To do this in Interface Builder, select the text view, uncheck Scrolling Enabled in the Attributes Inspector, and add the constraints manually.

Note: If you have other view/s above/below your text view, consider using a UIStackView to arrange them all.


Here's a solution for people who prefer to do it all by auto layout:

In Size Inspector:

  1. Set content compression resistance priority vertical to 1000.

  2. Lower the priority of constraint height by click "Edit" in Constraints. Just make it less than 1000.

enter image description here

In Attributes Inspector:

  1. Uncheck "Scrolling Enabled"


UITextView doesn't provide an intrinsicContentSize, so you need to subclass it and provide one. To make it grow automatically, invalidate the intrinsicContentSize in layoutSubviews. If you use anything other than the default contentInset (which I do not recommend), you may need to adjust the intrinsicContentSize calculation.

@interface AutoTextView : UITextView@end

#import "AutoTextView.h"@implementation AutoTextView- (void) layoutSubviews{    [super layoutSubviews];    if (!CGSizeEqualToSize(self.bounds.size, [self intrinsicContentSize])) {        [self invalidateIntrinsicContentSize];    }}- (CGSize)intrinsicContentSize{    CGSize intrinsicContentSize = self.contentSize;    // iOS 7.0+    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0f) {        intrinsicContentSize.width += (self.textContainerInset.left + self.textContainerInset.right ) / 2.0f;        intrinsicContentSize.height += (self.textContainerInset.top + self.textContainerInset.bottom) / 2.0f;    }    return intrinsicContentSize;}@end