我有一个UIView
,我使用Xcode Interface Builder设置约束。
现在,我需要以编程方式更新该实例的高度常量。
有一个函数类似myUIView.updateConstraint()
,但我不知道如何使用它。
从“Interface builder”中选择高度约束并获取其出口。因此,当您想要更改视图的高度时,可以使用以下代码。
yourHeightConstraintOutlet.constant = someValue
yourView.layoutIfNeeded()
方法updateConstraints()是UIView的一个实例方法。当您以编程方式设置约束时,它很有用。它会更新视图的约束。有关更多详细信息,请单击此处。
如果您有一个具有多个约束的视图,那么无需创建多个出口的更简单的方法是:
在interface builder中,为要修改的每个约束指定一个标识符:
然后在代码中可以修改多个约束,如下所示:
for constraint in self.view.constraints {
if constraint.identifier == "myConstraint" {
constraint.constant = 50
}
}
myView.layoutIfNeeded()
您可以为多个约束指定相同的标识符,从而允许您将约束分组并一次修改所有约束。
更改高度约束和宽度约束,而不创建IBOutlet。
注意:在序列图像板或XIB文件中指定高度或宽度约束。使用此扩展获取此约束后。
可以使用此扩展获取高度和宽度约束:
extension UIView {
var heightConstraint: NSLayoutConstraint? {
get {
return constraints.first(where: {
$0.firstAttribute == .height && $0.relation == .equal
})
}
set { setNeedsLayout() }
}
var widthConstraint: NSLayoutConstraint? {
get {
return constraints.first(where: {
$0.firstAttribute == .width && $0.relation == .equal
})
}
set { setNeedsLayout() }
}
}
您可以使用:
yourView.heightConstraint?.constant = newValue