简体   繁体   English

如何以编程方式使用UIScrollView进行UIStackView滚动?

[英]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. 我已经看到了几个使用UIScrollView进行UIStackView滚动的解决方案,但它们都依赖于Autolayout和IB。

Is there a way to do it programmatically? 有没有办法以编程方式进行?

I have seen this example: https://gist.github.com/twostraws/a02d4cc09fc7bc16859c 我见过这个例子: https//gist.github.com/twostraws/a02d4cc09fc7bc16859c

But it uses Visual Format Language and I am using the Layout Anchor API. 但它使用Visual Format语言,我正在使用Layout Anchor API。

The layout anchor API: 布局锚点API:

view.leadingAnchor.constraintEqualToAnchor(otherview.topAnchor).active = true

You can try ScrollableStackView : https://github.com/gurhub/ScrollableStackView 您可以尝试ScrollableStackViewhttps//github.com/gurhub/ScrollableStackView

Sample Code (Swift) 示例代码(Swift)

import ScrollableStackView

var scrollable = ScrollableStackView(frame: view.frame)
view.addSubview(scrollable)

// add your views with 
let rectangle = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 55))
rectangle.backgroundColor = UIColor.blue
scrollable.stackView.addArrangedSubview(rectangle)
// ...

Sample Code (Objective-C) 示例代码(Objective-C)

@import ScrollableStackView

ScrollableStackView *scrollable = [[ScrollableStackView alloc] initWithFrame:self.view.frame];
scrollable.stackView.distribution = UIStackViewDistributionFillProportionally;
scrollable.stackView.alignment = UIStackViewAlignmentCenter;
scrollable.stackView.axis = UILayoutConstraintAxisVertical;
[self.view addSubview:scrollable];

UIView *rectangle = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 55)];
[rectangle setBackgroundColor:[UIColor blueColor]];

// add your views with
[scrollable.stackView addArrangedSubview:rectangle]; 
// ...

Hope it helps. 希望能帮助到你。

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 : 总而言之,将UIStackView嵌入到UIScrollView ,并通过设置UIStackView的锚约束以匹配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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM