I am trying to place UITextView inside UIScrollView with AutoLayout with no luck. What I have tried is,
- I placed UIScrollView inside the main view in Storyboard
- I placed UITextView inside UIScrollView in Storyboard and disabled Scrolling Enabled
- I set constraints (leading, trailing, top, bottom) on UIScrollView
- I set constraints (top, leading, trailing, height) on UITextView
- I created IBOutlet of height constraint of UITextView
- I set a text (a lot of text which can cause scrolling) on UITextView in viewDidLoad()
- I set a height constraint of UITextView with the code below. I have tried it right after setting text in viewDidLoad() and viewDidLayoutSubviews() with no luck
self.textViewHeightConstraint.constant = [self.textView sizeThatFits:CGSizeMake(self.textView.frame.size.width, FLT_MAX)].height;
UITextView is getting its height, but UIScrollView isn't. Is there anything I've missed?
I have working example of how to calculate height for UITextView dynamic height + it's inside UIStackView which is inside UIScrollView here: https://github.com/fassko/ScrollStackViewExample
It seems that this question has an answer that has worked for a number of people. However, it should be noted that the documentation states:
Before trying to put a
UITextView
in aUIScrollView
you should consider if this is really necessary. If the text view is part of a complex layout within the scroll view, then note the use of theUIView
container in the accepted answer.See also: Scroll Views Inside Scroll Views
After a few days of research and getting my hands dirty with UIScrollView + UITextView + Auto Layout, I successfully got a fully working UIScrollView. I want to share my solution just in case someone might stuck on the same situation.
@property (nonatomic, weak) IBOutlet NSLayoutConstraint *textViewHeightConstraint;
and connect it in Storyboardself.textViewHeightConstraint.constant = [self.textView sizeThatFits:CGSizeMake(self.textView.frame.size.width, CGFLOAT_MAX)].height;
After all of these 10 steps, you'll get fully working UIScrollView with UITextView inside and be happy.