如何将标识符添加到自动布局锚点约束?
问题描述:
我想添加标识符到我所有的约束,所以我可以调试一个问题。问题是如果我使用锚点,我不会直接创建所有的约束条件。 我可以创建一个约束:如何将标识符添加到自动布局锚点约束?
let constraint = NSLayoutConstraint(item: view, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 60.0)
但后来我不得不把它添加到视图,而不是heightAnchor(没有与UIStackViews相关联的.addConstraint()方法)
那么怎么办我想补充标识符和由这几行代码自动生成的约束:
view.heightAnchor.constraint(equalToConstant: 60.0).isActive = true
view.widthAnchor.constraint(equalToConstant: 60.0).isActive = true
锚是为了使编程自动布局更容易,但肯定不是在暂时无法正常调试费用? 如果我不能添加标识符,我该如何调试我的“不可满足”约束异常?
答
你的代码返回你约束,这样你就可以像这样
let myConstraint = view.heightAnchor.constraint(equalToConstant: 60.0)
myConstraint.identifier = "myIdentifier"
myConstraint.isActive = true
答
看看我给出的question的答案。它会给你一个你的问题的答案。
(没有.addConstraint()方法
是的,有:
NSLayoutConstraint.activate([constraintvariable])
编辑:
好吧,如果我正确地理解你的问题:
let vHeightConstraint = self.view.heightAnchor.constraint(equalToConstant: 60.0);
vHeightConstraint.isActive = true
vHeightConstraint.identifier = "Your identifier"
通过这种方式,您将拥有一个用于约束的变量,并且可以在调试下查看它的值。
答
我使用数组和激活/停用他们将其添加标识:
var p = [NSLayoutConstraint]() // portrait constraints
var l = [NSLayoutConstraint]() // landscape constraints
// (an example of this) pin segmentedView to top
p.append(segmentedControl.topAnchor.constraint(equalTo: imageLayout.topAnchor))
p.append(segmentedControl.widthAnchor.constraint(equalToConstant: 300))
p.append(segmentedControl.centerXAnchor.constraint(equalTo: imageLayout.centerXAnchor))
l.append(segmentedControl.topAnchor.constraint(equalTo: imageLayout.topAnchor))
l.append(segmentedControl.widthAnchor.constraint(equalToConstant: 300))
l.append(segmentedControl.centerXAnchor.constraint(equalTo: imageLayout.centerXAnchor))
public func setOrientation(_ p:[NSLayoutConstraint], _ l:[NSLayoutConstraint]) {
NSLayoutConstraint.deactivate(l)
NSLayoutConstraint.deactivate(p)
if self.bounds.width > self.bounds.height {
NSLayoutConstraint.activate(l)
} else {
NSLayoutConstraint.activate(p)
}
}
你的想法....将约束移动到数组中并根据需要激活/停用。
+0
非常好,的确!谢谢! – Mozahler
啊。我认为这是创造了多个约束(可能是他们的一个数组)。谢谢你的帮助! – Mozahler