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

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

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

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

This question is related to swift xcode autolayout nslayoutconstraint

The answer is


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

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

myConstraint.constant = newValue
myView.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()
})

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.


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

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 

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

}

Examples related to swift

Make a VStack fill the width of the screen in SwiftUI Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Command CompileSwift failed with a nonzero exit code in Xcode 10 Convert Json string to Json object in Swift 4 iOS Swift - Get the Current Local Time and Date Timestamp Xcode 9 Swift Language Version (SWIFT_VERSION) How do I use Safe Area Layout programmatically? How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator Safe Area of Xcode 9 The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

Examples related to xcode

Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64 iPhone is not available. Please reconnect the device Make a VStack fill the width of the screen in SwiftUI error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65 The iOS Simulator deployment targets is set to 7.0, but the range of supported deployment target version for this platform is 8.0 to 12.1 Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools) Xcode 10: A valid provisioning profile for this executable was not found Xcode 10, Command CodeSign failed with a nonzero exit code

Examples related to autolayout

Autoresize View When SubViews are Added How to update the constant height constraint of a UIView programmatically? Getting a "This application is modifying the autolayout engine from a background thread" error? Programmatically Add CenterX/CenterY Constraints How to trap on UIViewAlertForUnsatisfiableConstraints? How to add constraints programmatically using Swift UICollectionView Self Sizing Cells with Auto Layout Automatic Preferred Max Layout Width is not available on iOS versions prior to 8.0 Remove all constraints affecting a UIView How do I programmatically set device orientation in iOS 7?

Examples related to nslayoutconstraint

How to update the constant height constraint of a UIView programmatically? Programmatically Add CenterX/CenterY Constraints How to add constraints programmatically using Swift UITextView that expands to text using auto layout Unable to simultaneously satisfy constraints, will attempt to recover by breaking constraint