Will Haley
Will Haley

Reputation: 763

Increase View Height In Scrollview Using Auto Layout

view controller with constraints

All the views here (except the nav bar) are in a scroll view. All the scrollview's children have pinned heights and vertical spacing set between them. The top label (Thanks for using...) and bottom button (Toggle) are vertically pinned to the scrollview at the top and bottom respectively. The bottom button is also pinned to the bottom layout guide.

I want a flexible height on the red view. The red view is the only one with an inequality constraint. Height >= 64

The flexible height is working in that the height of the red view automatically expands to 152 to fill the extra space on 4'' devices.

However, I want to expand the height even more. In code, I want to expand the height of that red view to, let's say, 300 when someone taps the Toggle button.

- (IBAction)toggle:(id)sender
{
    [self.scrollView layoutIfNeeded];
    [UIView animateWithDuration:1.0 animations:^{
        self.constraint.constant = 300;
        [self.scrollView layoutIfNeeded];
    }];
}

When I do this, I get an error in the console. "Unable to simultaneously satisfy constraints." Ending with, "Will attempt to recover by breaking constraint " and it breaks the constraint that I just set for the height of 300.

So....how DO I set the height of that red view to something larger like 300? I assumed if I updated it's height contraint that the contentSize of the scrollView would automatically adjust, but that does not seem to be happening.

Upvotes: 1

Views: 1534

Answers (1)

bilobatum
bilobatum

Reputation: 8918

You are setting the height of the constraint in code correctly. However, your layout needs some tweaking to get this to work properly.

It looks like you're adding the subviews to the scroll view itself. Instead, you need to add a content view to the scroll view, then add subviews to the content view.

For more information about how to use Auto Layout with a UIScrollView, check out Apple's technical note: developer iOS technotes

In your particular case, I would use Apple's so-called "Mixed Approach". In this approach, you set the content view's frame and the scroll view's content size directly. Calculating the height will be a pain. This involves calculating the height of every individual subview plus margins and spacers.

Upvotes: 1

Related Questions