Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make UIStackView scroll with UIScrollView programmatically?

I have seen several solutions to make UIStackView scroll with UIScrollView but they all rely Autolayout and IB.

Is there a way to do it programmatically?

I have seen this example: https://gist.github.com/twostraws/a02d4cc09fc7bc16859c

But it uses Visual Format Language and I am using the Layout Anchor API.

The layout anchor API:

view.leadingAnchor.constraintEqualToAnchor(otherview.topAnchor).active = true
like image 505
Roymunson Avatar asked Jul 01 '26 14:07

Roymunson


1 Answers

I was looking to do the same thing and stumbled upon this excellent post. To summarize, embed your UIStackView in your UIScrollView, and continue in the direction you were thinking by setting the anchor constraints of the UIStackView to match those of the UIScrollView:

stackView.leadingAnchor.constraintEqualToAnchor(scrollView.leadingAnchor).active = true
stackView.trailingAnchor.constraintEqualToAnchor(scrollView.trailingAnchor).active = true
stackView.bottomAnchor.constraintEqualToAnchor(scrollView.bottomAnchor).active = true
stackView.topAnchor.constraintEqualToAnchor(scrollView.topAnchor).active = true
stackView.widthAnchor.constraintEqualToAnchor(scrollView.widthAnchor).active = true
like image 76
Dalmazio Avatar answered Jul 03 '26 05:07

Dalmazio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!