Using UIScrollView in Swift5 with Autolayout
Four simple steps to get started with UIScrollView in your iOS App
Apple has updated the UIScrollView
in iOS11 by the two guides:
contentLayoutGuide
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
.
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!