无法获取 NSLayoutConstraint 的约束
Unable to get constraints of NSLayoutConstraint
这是我的代码:
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: {[=10=].constant == -5 }))
这是我的印刷品:
-5.0
nil
如何在代码中恢复该约束?为什么它打印出零?我想稍后为约束的常量设置动画。谢谢
使用 class 级变量来保存要修改的约束。如果您使用故事板/Interface Builder,您还可以将约束分配为 IBOutlet。
class ViewController: UIViewController {
var constraintToAnimate: NSLayoutConstraint?
override func viewDidLoad() {
super.viewDidLoad()
constraintToAnimate = NSLayoutConstraint(item: some, attribute: fromAttribute, relatedBy: NSLayoutRelation.equal, toItem: some2, attribute: toAttribute, multiplier: multiplier, constant: -5)
constraintToAnimate.isActive = true
}
// later, perhaps in a button tap...
func animateIt() {
constraintToAnimate?.constant = 100
}
}
让我们从核心问题开始:
如何在代码中恢复该约束?
理想情况下,您不需要。创建它时将其保存到变量中,例如:
var myConstraint: NSLayoutConstraint?
func x() {
let b = NSLayoutConstraint(...)
...
myConstraint = b
}
为什么打印出来的是nil?
当设置isActive = true
时,约束被添加到最近的公共父视图。例如,如果 A
是 B
的父视图并且您有一个相同宽度的约束,那么该约束将添加到 A
并且它不会出现在 B
.
仅当 some2
是 some
的子视图时才会将约束添加到 some
。
这是我的代码:
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: {[=10=].constant == -5 }))
这是我的印刷品:
-5.0
nil
如何在代码中恢复该约束?为什么它打印出零?我想稍后为约束的常量设置动画。谢谢
使用 class 级变量来保存要修改的约束。如果您使用故事板/Interface Builder,您还可以将约束分配为 IBOutlet。
class ViewController: UIViewController {
var constraintToAnimate: NSLayoutConstraint?
override func viewDidLoad() {
super.viewDidLoad()
constraintToAnimate = NSLayoutConstraint(item: some, attribute: fromAttribute, relatedBy: NSLayoutRelation.equal, toItem: some2, attribute: toAttribute, multiplier: multiplier, constant: -5)
constraintToAnimate.isActive = true
}
// later, perhaps in a button tap...
func animateIt() {
constraintToAnimate?.constant = 100
}
}
让我们从核心问题开始:
如何在代码中恢复该约束?
理想情况下,您不需要。创建它时将其保存到变量中,例如:
var myConstraint: NSLayoutConstraint?
func x() {
let b = NSLayoutConstraint(...)
...
myConstraint = b
}
为什么打印出来的是nil?
当设置isActive = true
时,约束被添加到最近的公共父视图。例如,如果 A
是 B
的父视图并且您有一个相同宽度的约束,那么该约束将添加到 A
并且它不会出现在 B
.
仅当 some2
是 some
的子视图时才会将约束添加到 some
。