Search code examples
iosxcodeuitextviewsizetofit

iOS: UITextView set height equal to content height


I have a UITextView with disabled scrolling and I need to set the height of the UITextView to match the height of the text content. I have tried various methods found the internet with no results. This is my code for the layout of the UITextView:

-(void) viewDidLayoutSubviews {
    // UITextView is named jobDescrip
    jobDescrip.scrollEnabled = NO;
    [jobDescrip sizeToFit];
    [jobDescrip layoutIfNeeded];
}

I have also tried this code in the viewDidAppear: method. Can someone please post code for an iOS 7.0 and later solution to this problem using auto layout?


Solution

  • Have you tried this? I added a button, with the flowing code in its action method I can see the height is changed to the text height.

    CGSize size = [self.textView systemLayoutSizeFittingSize:self.textView.contentSize];
    CGRect frame = self.textView.frame;
    frame.size.height = size.height;
    self.textView.frame = frame;
    

    Edit

    I added a bottom space to superview constraint and set it as IBOutlet property,then in viewDidAppear I changed the constraint constant.

    - (void)viewDidAppear:(BOOL)animated
    {
        [super viewDidAppear:animated];
        self.textView.contentInset = UIEdgeInsetsZero;
        CGSize size = [self.textView systemLayoutSizeFittingSize:self.textView.contentSize];
        self.heightConstraint.constant -= size.height - self.textView.frame.size.height;
        self.textView.scrollEnabled = NO;
        [self.textView setNeedsUpdateConstraints];
    }