It is fairly easy to use UIScrollView with the AutoLayout on iOS 12+ but only if one follows the following steps ...

It is fairly easy to use UIScrollView with the AutoLayout on iOS 12+ but only if one follows the following steps:

  1. Add UIScrollView and pin it 0,0,0,0 to superview (or your desired size)
NSLayoutConstraint.activate([
    scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
    scrollView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
    scrollView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
    scrollView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor)
])
  1. Add UIView in ScrollView, pin it 0,0,0,0 to all 4 sides.
NSLayoutConstraint.activate([
    contentView.topAnchor.constraint(equalTo: scrollView.contentLayoutGuide.topAnchor),
    contentView.bottomAnchor.constraint(equalTo: scrollView.contentLayoutGuide.bottomAnchor),
    contentView.leadingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.leadingAnchor),
    contentView.trailingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.trailingAnchor)
])
  1. Center contentView X and Y and set Y’s priority to low. Set contentView height to greaterThanOrEqualTo it’s parent height.
let contentViewCenterY = contentView.centerYAnchor.constraint(equalTo: scrollView.centerYAnchor)
contentViewCenterY.priority = .defaultLow

let contentViewHeight = contentView.heightAnchor.constraint(greaterThanOrEqualTo: view.heightAnchor)
contentViewHeight.priority = .defaultLow

NSLayoutConstraint.activate([
    contentView.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor),
    contentViewCenterY,
    contentViewHeight
])
  1. Add all views that you need into this view. Don’t forget to set the bottom constraint on the lowest view.

The source code can be found here: seifeet/SwiftFormScrolling

FAQ

How do I set up UIScrollView with Auto Layout in code so it scrolls correctly?
Pin the UIScrollView to the view's safe area on all four sides, add a contentView inside it, and constrain the contentView to the contentLayoutGuide on all edges. Then center the contentView and give it a height greater than or equal to the parent so Auto Layout can compute the scrollable content size.
Why do I need to center the content view and use low-priority height constraints?
Centering the content view with a low-priority vertical constraint lets it stay centered when content is short but still expand beyond the scroll view when content grows. The greaterThanOrEqualTo height constraint ensures the content is at least as tall as the scroll view without over-constraining the layout.

Welcome to The infinite monkey theorem

Somewhere a monkey just typed Shakespeare in TypeScript. Be the first to read the masterpieces (and the hilarious misfires) landing on the blog.

Subscribe to The infinite monkey theorem

We fling fresh posts—no banana peels attached—straight to your inbox.