How to update the constant height constraint of a

2020-01-24 20:17发布

I have a UIView and I set the constraints using Xcode Interface Builder.

Now I need to update that UIView's height constant programmatically.

There is a function that goes like myUIView.updateConstraints(), but I don't know how to use it.

9条回答
兄弟一词,经得起流年.
2楼-- · 2020-01-24 20:48

First connect the Height constraint in to our viewcontroller for creating IBOutlet like the below code shown

@IBOutlet weak var select_dateHeight: NSLayoutConstraint!

then put the below code in view did load or inside any actions

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

if it is inside a button click

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

}
查看更多
闹够了就滚
3楼-- · 2020-01-24 20:49

If you have a view with multiple constrains, a much easier way without having to create multiple outlets would be:

In interface builder, give each constraint you wish to modify an identifier:

enter image description here

Then in code you can modify multiple constraints like so:

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

You can give multiple constrains the same identifier thus allowing you to group together constrains and modify all at once.

查看更多
疯言疯语
4楼-- · 2020-01-24 20:50

If the above method does not work then make sure you update it in Dispatch.main.async{} block. You do not need to call layoutIfNeeded() method then.

查看更多
登录 后发表回答