A lot of questions are available with this but I'm very bad with constraints. So I've added a UIScrollView
and the UIView
I want to show has height of 700
and this is fixed 700 no dynamic height. The constraints I've for UIScrollView
are:
And for UIView
the constraints are:
But it's not scrolling.
When you are giving AutoLayout to a scrollView, follow the below methods.
Treat ScrollView like any other view object and apply the constraints like you normally do:
Get a view inside the scrollView which would later contain all the views you would want inside the ScrollView. Apply the constraints like you would apply to a subview, like below:
Apart from the leading, trailing,top and bottom constraints, the width and height are additionally specified. The width and height would define how much the ScrollView can scroll in the horizontal or vertical direction.
Instead of directly specifying the width and height, you might want to specify the height and width in relation with the other contents you might add inside this subview.
Tip : If you can draw a straight line from top to bottom, connecting the constraints of the Y axis constraints of the subviews, you will not get the ambiguos content error. Same is the case for width.
Programatically, you can follow the same approach:
You can increase the heightAnchor or widthAnchor of the scrollContentView according to your requirement.
Give the height to the contentView inside the scrollview not only to the scrollview itself
What I do when I need a scrollable view is what follows - just go over your constraints in storyboards and do the same there (especially pay attention to second step):
I add a
scrollView
to the hierarchy and use autolayout to properly layout it, e.g., if it is supposed to cover the wholeview
of theviewController
:Then you need to add a
contentView
to thescrollView
and provide a proper layout constraints for it, so if you want vertically scrollablescrollView
in the example I started above, you need following autolayout constraints:Notice here that I constrained the
leftAnchor
andrightAnchor
of thecontentView
to theself.view
rather than toscrollView
to make it of fixed width. However, top and bottom anchors are constrained to the scrollView, so they are expanded and scrollable whencontentView
needs more space.Now you add to the
contentView
all the content that you want, and you lay it out using autolayout as if thecontentView
was a view with infinite height. Or you can just explicitly set its height to 700 as you want.