我想以编程方式向视图添加约束。
这就是我所做的:
extension UIView {
func bottomToTop(other: UIView) {
self.translatesAutoresizingMaskIntoConstraints = false
other.translatesAutoresizingMaskIntoConstraints = false
let constraint = NSLayoutConstraint(
item: self,
attribute: .bottom,
relatedBy: .equal
toItem: other,
attribute: .top,
multiplier: 1.0,
constant: 0.0
)
superview?.addConstraint(constraint)
constraint.isActive = true
}
}
let label = UILabel()
label.text = "Lenaaaaa"
label.sizeToFit()
label.backgroundColor = .green
let label1 = UILabel()
label1.text = "Lena 2"
label1.sizeToFit()
label1.backgroundColor = .green
let uiView = UIView(frame: frame) (not zero)
uiView.addSubview(label)
uiView.addSubview(label2)
label.bottomToTop(label2)
为什么我会这样?
答案 0 :(得分:1)
为什么我会这样?
因为您的约束条件不明确。一旦您添加了影响视图的一个约束,您必须根据自动布局完全描述该视图的位置和大小。 (而且您必须停止谈论 .frame
,因为它现在实际上毫无意义。)
所以,你只说了
label.bottomToTop(label2)
但是你没有说label
的顶部在哪里,label
的左边在哪里,label2
的左边在哪里,等等。因此,自动布局引擎绝望地举起了双手。
只要运行您的应用程序并使用视图调试器,您就可以轻松地发现这一点。它会显示很大的感叹号,告诉您您的自动布局问题是什么。