我正在弄乱this以编程方式创建的滚动视图和堆栈视图的示例,我决定尝试将UIButtons更改为UILabels。我用以下代码替换了for循环中的代码:
let label = UILabel()
label.text = "Label"
stackView.addArrangedSubview(label)
然而,当我重新运行应用程序时,我发现滚动视图无法再滚动。调试后,我发现堆栈视图的frame
零宽度和零高度,我认为这是问题的根源。我一直无法弄清楚为什么堆栈视图没有宽度或高度,或者如何再次滚动滚动视图。
这里是全视图控制器,我修改为Swift 4编译它,使用UILabel,并打印帧大小:
import UIKit
class ViewController: UIViewController {
var scrollView: UIScrollView!
var stackView: UIStackView!
override func viewDidLoad() {
super.viewDidLoad()
scrollView = UIScrollView()
scrollView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(scrollView)
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[scrollView]|", options: .alignAllCenterX, metrics: nil, views: ["scrollView": scrollView]))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[scrollView]|", options: .alignAllCenterX, metrics: nil, views: ["scrollView": scrollView]))
stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
scrollView.addSubview(stackView)
scrollView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[stackView]|", options: NSLayoutFormatOptions.alignAllCenterX, metrics: nil, views: ["stackView": stackView]))
scrollView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[stackView]", options: NSLayoutFormatOptions.alignAllCenterX, metrics: nil, views: ["stackView": stackView]))
for _ in 1 ..< 100 {
let label = UILabel()
label.text = "Label"
label.sizeToFit()
stackView.addArrangedSubview(label)
// let vw = UIButton(type: UIButtonType.system)
// vw.setTitle("Button", for: .normal)
// stackView.addArrangedSubview(vw)
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
scrollView.contentSize = CGSize(width: stackView.frame.width, height: stackView.frame.height)
print("stack view frame: \(stackView.frame)")
}
}
答案 0 :(得分:1)
你应该:
•通过更新上一个VFL约束,将stackView
的底部固定到scrollView
的内容底边:
scrollView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[stackView]|", options: NSLayoutFormatOptions.alignAllCenterX, metrics: nil, views: ["stackView": stackView]))
•避免将自动布局与“手动”布局混合并删除该行:
scrollView.contentSize = CGSize(width: stackView.frame.width, height: stackView.frame.height)