How to make UIStackView scroll with UIScrollView programmatically?

耗尽温柔 提交于 2019-12-12 15:22:56

问题


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

回答1:


You can try ScrollableStackView : https://github.com/gurhub/ScrollableStackView

Sample Code (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)

@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.




回答2:


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


来源:https://stackoverflow.com/questions/37889408/how-to-make-uistackview-scroll-with-uiscrollview-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!