Using UIScrollView in Swift5 with Autolayout

Four simple steps to get started with UIScrollView in your iOS App

Mohannad Bakbouk
Next Level Swift

--

Photo by cottonbro from Pexels

Apple has updated the UIScrollView in iOS11 by the two guides:

  1. contentLayoutGuide
  2. frameLayoutGuide

Today I will explain how to set up auto layout constraints for UIScrollView.

The Implementation

We start by adding a UIScrollView to our ViewController and adding four constraints with 0 to the SafeArea.

The ScrollView should look like this after the constraints are set to 0

Next, we are adding a plain UIView into our UIScrollView. I will be calling it content.

For alignment, we now have to add four constraints to the content view’s edges with contentLayoutGuide and set their constant value to zero.

Finally, we add size constraints to the content view. Do so by setting equal widths and equal height constraint with frameLayoutGuide. This is important: We want to change the priority of our equal height constraint from 1000 to 750. This allows us to scroll whenever we have content higher than the original size.

Your constraints should now look like this:

Conclusion

We’ve set up UIScrollView’s constraints in such a way that Xcode stops complaining! Using a ScrollView wherever there is more extensive content available reduces the risk of clipping content at the bottom of the screen! Remember that there are still iPhones available that have a smaller screen than the iPhone 12 Pro Max!

We are always looking for talented and passionate Swift developers! Feel free to check out our writer’s section and find out how you can share your knowledge with the Next Level Swift Community!

--

--