UIButton 是UIView 的子类,因此它有一个constraints 属性,即[NSLayoutConstraint]。
您创建的NSLayoutConstraint 是一个对象(因此它是在堆上分配的)并且对它的引用被添加到按钮本身的constraints 属性中:
let button = UIButton()
print(button.constraints)
[] // empty array
button.widthAnchor.constraint(equalToConstant:44.0).isActive = true
print(button.constraints)
[<NSLayoutConstraint:0x6000000926b0 UIButton:0x7fbe6ff01940.width == 44 (active)>]
NSLayoutConstraint 最多与两个项目(视图)相关。
当您激活NSLayoutConstraint 时,iOS 会将对该约束的引用添加到相应UIView 子类的constraints 属性中。合适的视图取决于约束中两项的关系。
relationship add to
------------ ------
siblings parent of the two siblings
parent/child parent
single view view
other first common ancestor
第一个只是最后一个的特定情况,但为了清楚起见,我把它留在这里。
兄弟姐妹示例
这是一个兄弟姐妹的例子。 button1 和button2 是container 的子视图,因此将button1 的高度与button2 的高度相关的约束的引用添加到constraints 数组中,container 是它们的父级观点:
let button1 = UIButton()
let button2 = UIButton()
let container = UIView()
container.addSubview(button1)
container.addSubview(button2)
button1.heightAnchor.constraint(equalTo: button2.heightAnchor, multiplier: 2).isActive = true
print(container.constraints)
[<NSLayoutConstraint:0x60800008ef10 UIButton:0x7f9ec7c03740.height == 2*UIButton:0x7f9ec7d06f90.height (active)>]