我正在尝试在运行时基于结构化(XML)数据生成UIScrollView
中显示的视图。我生成了我需要的所有视图,然后将它们添加到我的scrollview中,使用自动布局让scrollview计算其contentSize
。只要我只使用UILabels
和自定义UIImageView
子类,一切都运行正常,但现在我想添加一个包含另一个视图和标签的嵌套视图来表示左边有垂直线的文本侧。
用于将所有生成的视图添加到scrollview的常规布局代码如下:
var previousAnchor = scrollView.topAnchor
views.forEach { (view) in
scrollView.addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
view.topAnchor.constraint(equalTo: previousAnchor,
constant: UI.defaultPadding).isActive = true
view.leadingAnchor.constraint(equalTo: self.view.leadingAnchor,
constant: UI.smallPadding).isActive = true
view.trailingAnchor.constraint(equalTo: self.view.trailingAnchor,
constant: -UI.smallPadding).isActive = true
previousAnchor = view.bottomAnchor
}
scrollView.bottomAnchor.constraint(equalTo: previousAnchor,
constant: UI.defaultPadding).isActive = true
我的嵌套子视图的布局代码如下所示(它是UIView
子类):
addSubview(label)
addSubview(line)
line.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10).isActive = true
line.topAnchor.constraint(equalTo: topAnchor).isActive = true
line.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
line.widthAnchor.constraint(equalToConstant: 2).isActive = true
line.trailingAnchor.constraint(equalTo: label.leadingAnchor).isActive = true
line.backgroundColor = UIColor.green
label.topAnchor.constraint(equalTo: topAnchor).isActive = true
label.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
label.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
label.numberOfLines = 0
label.text = "Here's to the crazy ones. The misfits. The rebels. The troublemakers."
如果我使用此代码,我根本无法在我的scrollview中看到此视图,并且scrollview在Debug View Hierarchy视图中附加了一个含糊不清的内容大小的警告。这有点令人恼火,因为在没有嵌套在像这样的视图中使用标签确实像魅力一样工作。所以我开始玩游戏,真正令我困惑的是,如果我使用下面的代码,我可以看到视图本身(因为我给它一个灰色的背景颜色),但仍然看不到行和/或标签,如在检查时,两者似乎都有一个(0,0,0,0)的框架:
addSubview(label)
addSubview(line)
line.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10).isActive = true
line.topAnchor.constraint(equalTo: topAnchor, constant: 10).isActive = true
line.widthAnchor.constraint(equalToConstant: 20).isActive = true
line.heightAnchor.constraint(equalToConstant: 20).isActive = true
line.trailingAnchor.constraint(equalTo: label.leadingAnchor).isActive = true
line.backgroundColor = UIColor.green
label.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
label.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
heightAnchor.constraint(equalToConstant: 100).isActive = true
heightAnchor.constraint(equalTo: label.heightAnchor).isActive = true
label.numberOfLines = 0
label.text = "Here's to the crazy ones. The misfits. The rebels. The troublemakers."
我错过了什么?我还尝试将所有视图放入容器视图中,而不是直接将它们用作scrollview的子视图,但这对我的嵌套视图没有帮助,并带来了其他问题。