问题描述
我见过几种使 UIStackView
与 UIScrollView
一起滚动的解决方案,但它们都依赖于 Autolayout 和 IB.
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?
我见过这个例子:https://gist.github.com/twostraws/a02d4cc09fc7bc16859c
但它使用可视化格式语言,而我使用的是布局锚点 API.
But it uses Visual Format Language and I am using the Layout Anchor API.
布局锚点 API:
view.leadingAnchor.constraintEqualToAnchor(otherview.topAnchor).active = true
推荐答案
我本来想做同样的事情,但偶然发现了这个 优秀的帖子. 总而言之,将您的 UIStackView
嵌入到您的 UIScrollView
中,然后通过设置UIStackView
的锚点约束以匹配 UIScrollView
的锚点约束:
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
这篇关于如何以编程方式使用 UIScrollView 使 UIStackView 滚动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!