Home Ask Login Register

Developers Planet

Your answer is one click away!

GeigerGeek February 2016

AutoLayout Scrolling UITextView sizeThatFits not working

In my UIViewController, I have a non-editable attributed UITextView with scrolling enabled, and I would like to resize the height of the scrolling text to accommodate all screen size widths without having extra white space. I am using AutoLayout and set up outlets for the textview and its height constraint. In the view controller's viewDidLoad method I use the sizeThatFits method to update the textview height, but the resulting size is too small.

- (void)viewDidLoad{
    [super viewDidLoad];
    NSLog(@"INIT HEIGHT: %f, myTextView.frame.size.height);
    CGSize sizeToFit =
    [myTextView sizeThatFits: CGSizeMake(myTextView.frame.size.width, MAXFLOAT)];
    myTextViewHeightConstraint.constant = sizeToFit.height;
    [myTextView updateConstraints];
    [myTextView layoutIfNeeded];
    NSLog(@"NEW HEIGHT: %f", myTextView.frame.size.height);

The log indicates the height was indeed changed from my default of 4000 to 2502, but with 2502 I only see about half of my text via scrolling. I am avoiding nesting the text view in a scroll view, as one solution suggests, since this is discouraged in documentation. What am I missing? Thanks in advance.


GeigerGeek February 2016

I found that the frame of a UITextView will automatically size to its content, so dynamically setting it is not necessary. sizeThatFits is a UIView method and doesn't modify the size of the text content, but rather the size of the window that the text appears in. The only code I needed was to scroll the text to the top:

    [myTextView scrollRectToVisible: CGRectMake(0,0,1,1) animated:NO];

This, as well as any Autolayout constraint updates shouldn't be made in viewDidLoad, but rather in viewDidLayoutSubviews or viewWillAppear. Best placement could probably be explained better - I'm open to comments.

Post Status

Asked in February 2016
Viewed 3,913 times
Voted 5
Answered 1 times


Leave an answer

Quote of the day: live life