我在滚动视图中有一个视图:
现在,我想以编程方式将子视图添加到该视图。多数民众赞成在我的代码来做到这一点:
子视图(工作)
//Adds header to the view again because it was removed in the clear() method
//Header is just a label
lv.addSubview(header)
header.leadingAnchor.constraint(equalTo: header.superview!.leadingAnchor).isActive = true
header.topAnchor.constraint(equalTo: header.superview!.topAnchor, constant: 2).isActive = true
header.widthAnchor.constraint(equalTo: header.superview!.widthAnchor).isActive = true
header.heightAnchor.constraint(equalToConstant: MainTabViewController.fontSize*3).isActive = true //Just a constant
现在我重复执行此代码:
private func makeTextLabel(text: NSAttributedString, bgColor: UIColor?, maxWidth: CGFloat?) -> UILabel {
//Creates label
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
lv.addSubview(label)
//Adjustments
if(bgColor != nil) {
label.backgroundColor = bgColor
}
label.textColor = UIColor.black
label.attributedText = text
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
let width = maxWidth ?? lv.frame.size.width-8
label.widthAnchor.constraint(equalToConstant: width).isActive = true
label.heightAnchor.constraint(equalToConstant: heightForLabel(attributedText: label.attributedText, width: width)).isActive = true
label.leadingAnchor.constraint(equalTo: lv.leadingAnchor, constant: 4).isActive = true
let previousView = lv.subviews[lv.subviews.count-1]
label.topAnchor.constraint(equalTo: previousView.bottomAnchor, constant: 10).isActive = true
return label
}
添加了所有标签,但约束根本不起作用。这是什么样子(当我两次执行以上方法时):
删除width
锚点。您不必在意宽度(您也不是很清楚),而是使用trailingAnchor
:
label.trailingAnchor.constraint(equalTo: lv.trailingAnchor, constant: -4).isActive = true
删除heightAnchor
,而是让系统为您计算高度:
label.setContentHuggingPriority(.required, for: .vertical)
label.setContentCompressionResistancePriority(.required, for: .vertical)
这应该是全部。
但是,作为旁注,您可以仅使用UIStackView
来代替对上一个标签创建约束,]