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

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


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 = someValueyourView.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.


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.


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 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() }}}

You can use:

yourView.heightConstraint?.constant = newValue