如何使用UIScrollView以编程方式滚动UIStackView?
我已经看到了几个解决scheme使UIStackView
滚动与UIScrollView
但他们都依靠Autolayout和IB。
有没有办法做到这一点编程?
我看过这个例子: https : //gist.github.com/twostraws/a02d4cc09fc7bc16859c
但它使用视觉格式语言,我正在使用布局锚API。
布局锚点API:
view.leadingAnchor.constraintEqualToAnchor(otherview.topAnchor).active = true
我期待着做同样的事情,并偶然发现这个优秀的职位。 总结一下,在你的UIScrollView
embedded你的UIStackView
,然后继续按照你所想的方向设置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
你可以试试ScrollableStackView : https : //github.com/gurhub/ScrollableStackView
示例代码(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) // ...
示例代码(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]; // ...
希望能帮助到你。