1

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.

enter image description here

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This somewhat works but their constraints are being changed way too later than they should be so that you can actually see it moving after the view has loaded. Is there a way to fix this problem?
Set the height constraint after set text. self.textviewHeightConstraint.constant = self.textview.contentSize.height;
3

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)];
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.