Horizontal Scrolling (UIStackView in UIScrollView)
For horizontal scrolling. First create a UIStackView and UIScrollView and add them to the view as follows:
let scrollView = UIScrollView() let stackView = UIStackView() scrollView.addSubview(stackView) view.addSubview(scrollView)
UIStackView not set translatesAutoresizingMaskIntoConstraints to false in UIStackView and UIScrollView :
stackView.translatesAutoresizingMaskIntoConstraints = false scrollView.translatesAutoresizingMaskIntoConstraints = false
For everything to work, the ending, leading, top and bottom UIStackView bindings must be equal to the UIStackView UIScrollView :
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 of the UIStackView binding must be equal to or greater than the width of the UIScrollView binding:
stackView.widthAnchor.constraint(greaterThanOrEqualTo: scrollView.widthAnchor).isActive = true
Now attach 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 aligning and distributing UIStackView :
topicStackView.axis = .horizontal topicStackView.distribution = .equalCentering topicStackView.alignment = .center topicStackView.spacing = 10
Finally, you need to use the addArrangedSubview: method to add subviews to your UIStackView.
Text inserts
Another useful feature that may turn out to be useful is that since the UIStackView contained in the UIScrollView you now have access to text inserts to make everything look a bit prettier.
let inset:CGFloat = 20 scrollView.contentInset.left = inset scrollView.contentInset.right = inset