Nesting a UIStackView within a UIScrollView: Horizontal Scrolling


Horizontal Scrolling (UIStackView within UIScrollView)

For horizontal scrolling. First, create a `UIStackView` and a `UIScrollView` and add them to your view in the following way:
let scrollView = UIScrollView()
let stackView = UIStackView()

scrollView.addSubview(stackView)
view.addSubview(scrollView)
Remembering to set the `translatesAutoresizingMaskIntoConstraints` to `false` on the `UIStackView` and the `UIScrollView`:
stackView.translatesAutoresizingMaskIntoConstraints = false
scrollView.translatesAutoresizingMaskIntoConstraints = false

To get everything working the trailing, leading, top and bottom anchors of the `UIStackView` should be equal to the `UIScrollView` anchors:
stackView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
stackView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
stackView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
stackView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
But the width anchor of the `UIStackView` must the equal to or greater than the width of the `UIScrollView` anchor:
stackView.widthAnchor.constraint(greaterThanOrEqualTo: scrollView.widthAnchor).isActive = true
Now anchor your `UIScrollView`, for example:
scrollView.heightAnchor.constraint(equalToConstant: 80).isActive = true
scrollView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true

scrollView.bottomAnchor.constraint(equalTo:view.safeAreaLayoutGuide.bottomAnchor).isActive = true
scrollView.leadingAnchor.constraint(equalTo:view.leadingAnchor).isActive = true
scrollView.trailingAnchor.constraint(equalTo:view.trailingAnchor).isActive = true 
Next, I would suggest trying the following settings for the `UIStackView` alignment and distribution:
topicStackView.axis = .horizontal
topicStackView.distribution = .equalCentering
topicStackView.alignment = .center

topicStackView.spacing = 10
 
Finally you'll need to use the `addArrangedSubview:` method to add subviews to your UIStackView.

Text Insets

One additional feature that you might find useful is that because the `UIStackView` is held within a `UIScrollView` you now have access to text insets to make things look a bit prettier.
let inset:CGFloat = 20
scrollView.contentInset.left = inset
scrollView.contentInset.right = inset
    
// remember if you're using insets then reduce the width of your stack view to match
stackView.widthAnchor.constraint(greaterThanOrEqualTo: topicScrollView.widthAnchor, constant: -inset*2).isActive = true

Comments