以编程方式创建 UILabel 堆栈
Posted
技术标签:
【中文标题】以编程方式创建 UILabel 堆栈【英文标题】:Programatically Creating a Stack of UILabels 【发布时间】:2018-02-20 22:34:26 【问题描述】:我正在搞乱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)")
【问题讨论】:
【参考方案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)
【讨论】:
我在踢自己;就是缺少一根管子。以上是关于以编程方式创建 UILabel 堆栈的主要内容,如果未能解决你的问题,请参考以下文章