UIKit: Programmatically embed a UIStackView in an UIScrollView using AutoLayout

Christof Zirkler
2 min readMar 21, 2021

--

In this article we want to find out how we can can lay out a horizontal UIStackView in an horizontally scrolling UIScrollView.

What we want to achieve: Programmatically nest a UIStackView in a ScrollView using auto layout

While we can use a UIStackView for creating user interfaces which dynamically adapt to the device’s orientation, screen size or any other changes in the available screen real estate, sometimes we just want to stack up a bunch of views in a given direction. In our case, we want to stack up some circles horizontally. The width of all the circles may exceed the available width of UIStackView, therefore we want to embed the UIStackView in an UIScrollView, to make the UIStackView scrollable. Let’s see how the end result looks like rendered on screen:

It’s quite straight forward to achieve this, all it takes is just a bit of AutoLayout and some constraining.

  1. We declare the horizontally stacking UIStackView with an item spacing of 20.
  2. Setup the UIScrollView, which adds the UIStackView as its subview.
  3. We add the UIScrollView to the ViewController’s view and constraint the scroll views leading and trailing anchor to leading and trailing edges of the view controller’s view. In this example, the scroll view has a height of 50 and a distance to to the top of 100.
  4. We are now constraining the edges of the stack view to the edges of the scroll view. By doing this, scroll view can derive the scroll direction.
  5. Finally we are adding some arranged subviews to the stackView. Those elements will then be scrollable, once the stack view’s width is greater than the available width of the scroll view.

Please find a copy & paste ready playground file for the described scenario here: https://gist.github.com/zirkler/d83f24aeffb332a47dc8372c90026e26

--

--

No responses yet