如何以编程方式更新 UIView 的恒定高度约束?

How to update the constant height constraint of a UIView programmatically?

我有一个 UIView 并且我使用 Xcode Interface Builder 设置了约束。

现在我需要以编程方式更新 UIView 实例的高度常量。

有个功能类似myUIView.updateConstraints(),但我不知道怎么用

要更新布局约束,您只需更新常量 属性 并在之后调用 layoutIfNeeded。

myConstraint.constant = newValue
myView.layoutIfNeeded()

将约束作为 IBOutlet 拖到 VC 中。然后您可以更改其关联值(和其他属性;查看文档):

@IBOutlet myConstraint : NSLayoutConstraint!
@IBOutlet myView : UIView!

func updateConstraints() {
    // You should handle UI updates on the main queue, whenever possible
    DispatchQueue.main.async {
        self.myConstraint.constant = 10
        self.myView.layoutIfNeeded()
    }
}

Select Interface builder 中的高度约束并取出它。所以,当你想改变视图的高度时,你可以使用下面的代码。

yourHeightConstraintOutlet.constant = someValue
yourView.layoutIfNeeded()

方法updateConstraints()UIView的实例方法。当您以编程方式设置约束时,它很有用。它更新视图的约束。有关详细信息,请单击 here

如果您有一个具有多个约束的视图,则无需创建多个出口的更简单的方法是:

在界面生成器中,为您希望修改的每个约束指定一个标识符:

然后在代码中你可以像这样修改多个约束:

for constraint in self.view.constraints {
    if constraint.identifier == "myConstraint" {
       constraint.constant = 50
    }
}
myView.layoutIfNeeded()

您可以为多个约束提供相同的标识符,从而允许您将约束组合在一起并一次修改所有约束。

如果上述方法不起作用,请确保在 Dispatch.main.async{} 块中更新它。您不需要调用 layoutIfNeeded() 方法。

首先将高度约束连接到我们的 viewcontroller 以创建 IBOutlet,如下面的代码所示

@IBOutlet weak var select_dateHeight: NSLayoutConstraint!

然后将下面的代码放在视图 did load 或任何操作中

self.select_dateHeight.constant = 0 // we can change the height value

如果它在按钮内点击

@IBAction func Feedback_button(_ sender: Any) {
 self.select_dateHeight.constant = 0

}

更改HeightConstraintWidthConstraint而不创建IBOutlet

注意: 在 Storyboard 或 XIB 文件中分配高度或宽度约束。使用此扩展获取此约束后。

您可以使用此扩展来获取高度和宽度约束:

extension UIView {

var heightConstraint: NSLayoutConstraint? {
    get {
        return constraints.first(where: {
            [=10=].firstAttribute == .height && [=10=].relation == .equal
        })
    }
    set { setNeedsLayout() }
}

var widthConstraint: NSLayoutConstraint? {
    get {
        return constraints.first(where: {
            [=10=].firstAttribute == .width && [=10=].relation == .equal
        })
    }
    set { setNeedsLayout() }
}

}

您可以使用:

yourView.heightConstraint?.constant = newValue 
Create an IBOutlet of NSLayoutConstraint of yourView and update the constant value accordingly the condition specifies.

//Connect them from Interface 
@IBOutlet viewHeight: NSLayoutConstraint! 
@IBOutlet view: UIView!

private func updateViewHeight(height:Int){
   guard let aView = view, aViewHeight = viewHeight else{
      return
   }
   aViewHeight.constant = height
   aView.layoutIfNeeded()
}

You can update your constraint with a smooth animation if you want, see the chunk of code below:

heightOrWidthConstraint.constant = 100
UIView.animate(withDuration: animateTime, animations:{
self.view.layoutIfNeeded()
})