lukas lukas - 1 year ago 76
iOS Question

Auto layout UIScrollView with subviews with dynamic heights

I'm having troubles with UIScrollView using auto layout constraints.
I have the following view hierarchy, with constraints set through IB:

- ScrollView (leading, trailing, bottom and top spaces to superview)
-- ContainerView (leading, trailing, bottom and top spaces to superview)
--- ViewA (full width, top of superview)
--- ViewB (full width, below ViewA)
--- Button (full width, below ViewB)

The ViewA and ViewB have initial heights of 200 points, but it can be expended vertically to an height of 400 points by clicking on it. ViewA and ViewB are expanded by updating their height constraint (from 200 to 400). Here is the corresponding snippet :

if(self.contentVisible) {
heightConstraint.constant -= ContentHeight;
// + additional View's internal constraints update to hide additional content
self.contentVisible = NO;
} else {
heightConstraint.constant += ContentHeight;
// + additional View's internal constraints update to show additional content
self.contentVisible = YES;

[self.view setNeedsUpdateConstraints];
[UIView animateWithDuration:.25f animations:^{
[self.view layoutIfNeeded];

My problem is that if both views are expanded, I need to be able to scroll to see the whole content, and right now the scroll is not working. How can I manage to update the scroll view using constraints to reflect the changes of ViewA and ViewB heights ?

The only solution I can think of so far is to manually set the height of the ContainerView after the animation, which will be the sum of the heights of ViewA + ViewB + Button. But I believe there is a better solution?


Answer Source

I use pure structure like the following

    -view A
    -view B

Make sure Button(THE LAST view) has a constraint(vertical spacing from its bottom to superview, which is the scrollview), in this case, no matter what changes for your view A and view B would be, scrollView's height will be changed accordingly.

I reference to this great online book site.

Just read the "Creating a scroll view" section, you should have an idea.

I had the similar problem that I was creating a detail view and using Interface Builder with Auto layout is such a good fit for the task!

Good luck!

(Additional resources:

Stack overflow discussion about the auto layout for scroll view.

iOS 6 has a Release Notes talking about Auto Layout support for UIScrollView.

Free online iOS book explanation about scroll view. This actually helped me a lot!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download