这是我的代码:
let b = NSLayoutConstraint(item: some, attribute: fromAttribute, relatedBy: NSLayoutRelation.equal, toItem: some2, attribute: toAttribute, multiplier: multiplier, constant: -5)
b.isActive = true
self.layoutIfNeeded()
print(b.constant)
print(some.constraints.first(where: {$0.constant == -5 }))
这是我的指纹:
-5.0
nil
我怎样才能在代码中恢复约束?为什么打印出来的是零?稍后我要设置约束常量的动画。谢谢。
最佳答案
让我们从核心问题开始:
我怎样才能在代码中恢复约束?
理想情况下,不需要。创建变量时将其保存到变量中,例如:
var myConstraint: NSLayoutConstraint?
func x() {
let b = NSLayoutConstraint(...)
...
myConstraint = b
}
为什么打印出来的是零?
设置
isActive = true
时,约束将添加到最近的公共超视图。例如,如果A
是B
的超视图,并且您具有相同的宽度约束,则该约束将添加到A
中,并且它不会出现在B
上。只有当
some
是some2
的子视图时,约束才会添加到some
中。关于ios - 无法获取NSLayoutConstraint的约束,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46352428/