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:25

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()
})
查看更多
迷人小祖宗
3楼-- · 2020-01-24 20:28

Drag the constraint into your VC as an IBOutlet. Then you can change its associated value (and other properties; check the documentation):

@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()
    }
}
查看更多
我想做一个坏孩纸
4楼-- · 2020-01-24 20:31

Select the height constraint from the Interface builder and take an outlet of it. So, when you want to change the height of the view you can use the below code.

yourHeightConstraintOutlet.constant = someValue
yourView.layoutIfNeeded()

Method updateConstraints() is an instance method of UIView. It is helpful when you are setting the constraints programmatically. It updates constraints for the view. For more detail click here.

查看更多
forever°为你锁心
5楼-- · 2020-01-24 20:36

To update a layout constraint you only need to update the constant property and call layoutIfNeeded after.

myConstraint.constant = newValue
myView.layoutIfNeeded()
查看更多
家丑人穷心不美
6楼-- · 2020-01-24 20:37

Change HeightConstraint and WidthConstraint Without creating IBOutlet.

Note: Assign height or width constraint in Storyboard or XIB file. after fetching this Constraint using this extension.

You can use this extension to fetch a height and width Constraint

extension UIView {

var heightConstaint: NSLayoutConstraint? {
    get {
        return constraints.first(where: {
            $0.firstAttribute == .height && $0.relation == .equal
        })
    }
    set { setNeedsLayout() }
}

var widthConstaint: NSLayoutConstraint? {
    get {
        return constraints.first(where: {
            $0.firstAttribute == .width && $0.relation == .equal
        })
    }
    set { setNeedsLayout() }
}

}

You can uses

yourView.heightConstaint?.constant = newValue 
查看更多
来,给爷笑一个
7楼-- · 2020-01-24 20:39
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()
}
查看更多
登录 后发表回答