iOS ScrollView needs constraint for y position or height
Xcode 11
I've been following several tutorials on this for a few hours now, and none of them seem to work. It seems that Xcode 11 has some updates that change how the scroll views work with auto layout.
- Add a
UIScrollView
to the view and add top, bottom, leading, and trailing constraints. - Add a
UIView
to the scroll view. We will call this the content view. - Add top, bottom, leading, and trailing constraints from the content view to the scroll view's Content Layout Guide. Set the constraints to 0.
- Add an equal width constraint between the content view and the scroll view's Frame Layout Guide. (Not the scroll view or the main view!)
- Temporarily add a height constraint to the content view so that you can add your content. Make sure that all content has top, bottom, leading, and trailing constraints.
Delete the height constraint on the content view.
I found an excellent tutorial at this link.
Whenever using ScrollView with auto layout always follow below steps,
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.
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.
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:
ContainerView constraints:
- Select your view controller
- Uncheck 'Adjust Scroll View Insets'