iOS ScrollView needs constraint for y position or height

Whenever using ScrollView with auto layout always follow below steps,

  1. ScrollView constraints: leadingSpace, topSpace, TrailingSpace, bottomSpace to superView and make sure when you control drag to add constraint, add it by pressing alt so that the constraint would be set without margin.

  2. Add UIView inside scroll view as container view and set its constraints:
    leadingSpace, topSpace, trailingSpace, bottomSpace to ScrollView without pressing alt button and set equalWidth to ScrollView.

  3. Whatever views you add inside this container view must have top to bottom constraint that is all view’s should have vertical constraint, so containerView can calculate height required for itself based on the content inside it.

If the constraints are set correctly then the scrollView will set its content size automatically based on the component inside it and you do not need to set the content size manually, also the scrollView will only scroll if the component inside the container view is not fitting inside otherwise it won’t scroll. If you want to make it scroll anyways then you need to check the Bounces Vertically property from storyboard to get the bounce effect.

Note: While you set constraint to the component inside the scrollView, you will see the constraint warning till you set the constraint from top component to the bottom one, aways remember that your top component should have top constraint (Vertical constraint) to superView and the component at the bottom should have bottom space constraint to the super view. When this satisfy then all warning will disappear eventually.

ScrollView constraints:

enter image description here

ContainerView constraints:

enter image description here

Leave a Comment

tech