I have a UIScrollView
that includes some components, and one of these components is a UITextView
, what I want is to let the UITextView
dynamically expands with the UIScrollView
, in fact I use autoLayout
, so this code is not working:
CGRect frame = self.detailTextView.frame;
frame.size.height = self.detailTextView.contentSize.height;
self.detailTextView.frame = frame;
scroll.contentSize = CGSizeMake(scroll.contentSize.width,
300 + self.detailTextView.frame.size.height);
[self.detailTextView setFrame:frame];
What I want is to help me doing this with storyboard elements.
Instead of setting the frame, drag one of the height constraints for your text view into your controller to create an outlet. Then in viewWillLayoutSubviews grab the contentSize and set the constant of your text view height constraint. That should accomplish what you're doing with the frame in your code above. Just be sure that your text view has constraints from all edges to your scroll view so that the scroll view can size itself properly.
in my case, what I did is kept the scrollview as super view and added all constraints for the subviews and the uitextview has constraint from all edges to the scrollview. then updated the content size in -viewDidLayoutSubviews method. here is the code snippet:
-(void)viewDidLayoutSubviews{
NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:12.0]};
CGRect rect = [_detailText.text boundingRectWithSize:CGSizeMake(_detailText.frame.size.width - 10.0, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
attributes:attributes
context:nil];
CGRect frame = _detailText.frame;
frame.size.height = ceil(rect.size.height) + _detailText.textContainerInset.top + _detailText.textContainerInset.bottom;
_detailText.frame = frame;
_detailText.contentSize = CGSizeMake(_detailText.frame.size.width, _detailText.frame.size.height);
[_contentScrollView setContentSize:CGSizeMake(_contentScrollView.frame.size.width, _detailText.frame.origin.y + _detailText.frame.size.height)];
}