Search code examples
iosuser-interfaceuiscrollviewautolayoutnslayoutconstraint

How to adjust uiscrollview after adding view (autolayout)


There is a UIScrollView in the main UIView. I have container UIView inside scrollview and its edges are pinned to scrollview. and this container view has constant width and height constraints. Because scroll view doesn't work without them.

When I add a lot of sub views inside the container view vertically the sub-views exceeds bottom border of container view. It is not scrollable cause container has the same predefined height. How make container view adjustable so it can match sub-views height that will make it scrollable.

Also consider that I am using autolayout.


Solution

  • What you actually need to do is to update the Height constraint, right?

    I would link the Height Constraint of your inside view as an IBOutlet in your ViewController :

    @property (nonatomic, weak)     IBOutlet    NSLayoutConstraint *contentViewHeight;
    
    • usual drag and drop to the File's Owner

    Then you'll need to update the Constant of your Constraint with a call of that method when you add your subviews inside:

    - (void)updateContentViewHeight:(CGFloat)height
    {
        self.contentViewHeight.constant = height;
        [self.yourContentView layoutIfNeeded]; 
    }
    

    If you can keep track of the Height of the whole stack of subviews, great! you just need to pass it to that method.

    If not, it may be a bit more tricky... You may need to remove the Height Constraint, add your subview one below each other (as long as their heights are fixed) without forgetting to "pin" the bottom border of the last Subview to the bottom border of the "inside view". In other words, the height of the inside view is not fixed but is expanded by the sum of its "height-fixed" content. This way after:

    [self.yourContentView layoutIfNeeded]; 
    

    It should have it's final Height in its ".frame"

    You should then be able to update the Height Constraint or set the content size of the scrollview, what ever works best for you.