在我的viewController viewDidLoad方法中,我有:
let stackView = UIStackView()
stackView.axis = .Vertical
self.view.addSubview(stackView)
for _ in 1..<100{
let vw = UIButton(type: .System)
vw.setTitle("Button", forState: .Normal)
stackView.addArrangedSubview(vw)
}
Run Code Online (Sandbox Code Playgroud)
但是当我编译时,我只得到一个完全白色的屏幕.我究竟做错了什么?
您正在将堆栈视图添加到父视图,但是您没有告诉父视图如何放置堆栈视图.如果您使用的是基于约束的布局,则需要将堆栈视图固定到父视图的某些边缘:
view.addConstraint(NSLayoutConstraint(item: stackView, Attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1.0, constant: 0.0)
view.addConstraint(NSLayoutConstraint(item: stackView, Attribute: .Leading, relatedBy: .Equal, toItem: self.view, attribute: .Leading, multiplier: 1.0, constant: 0.0)
view.addConstraint(NSLayoutConstraint(item: stackView, Attribute: .Trailing, relatedBy: .Equal, toItem: self.view, attribute: .Trailing, multiplier: 1.0, constant: 0.0)
Run Code Online (Sandbox Code Playgroud)
这会将堆栈视图固定到视图的顶部,前端和后端.
另一种方法是使用Interface Builder来设置约束,因为它们在代码中管理起来非常冗长.
| 归档时间: |
|
| 查看次数: |
4580 次 |
| 最近记录: |