31

I want to change the height constraint of a UITextView programmatically so I set the constraint as an outlet in my controller like this:

@property (strong, nonatomic) IBOutlet NSLayoutConstraint *descriptionHeightConstraint;

To change it I do the following:

self.descriptionHeightConstraint.constant = self.description.contentSize.height;

This works if I do it in viewDidAppear but the problem with this is that I can see how the height changes after the view displayed which is not very user friendly so I tried doing it in viewWillAppear but didn't work there, the height doesn't change. Calling setNeedsUpdateConstraints after changing the constraint didn't work either.

Why is working in viewDidAppear and not in viewWillAppear? Any workaround?

Thanks in advance!

mxch
  • 835
  • 2
  • 10
  • 20

1 Answers1

27

Try setting the constant in viewDidLayoutSubviews instead.

Note that using the text view's contentSize property to set the text view's height does not work in iOS 7. See https://stackoverflow.com/a/18837714/1239263

Community
  • 1
  • 1
bilobatum
  • 8,918
  • 6
  • 36
  • 50
  • 1
    Just tried that, in the iOS6 simulator works fine, the view display and the height is correct but in iOS7 I can see how the height changes after the view displayed. Maybe I'm doing something wrong? – mxch Jan 05 '14 at 04:55
  • Thank you very much! It worked with that, now I check if it is iOS7 and do as it is explained in the answer you posted. Thanks! – mxch Jan 05 '14 at 05:22
  • Thanks for your post. This fixed my same issue for iOS8, however, it crashes the app for iOS7. Any idea why? I'm still investigating. – Carlos Pinto May 09 '15 at 02:03
  • viewDidLayoutSubviews() WORKED after lots of searching!! thank you!! – devjme Apr 04 '17 at 19:40