Update height constraint programmatically
Instead of adding a new constraint, you need to modify the constant on your existing constraint.
Use an IBOutlet to connect to your constraint in Interface Builder:
@property (nonatomic, weak) NSLayoutConstraint *heightConstraint;
Then, when you need to set it programmatically, simply set the constant property on the constraint:
heightConstraint.constant = 100;
OR
If you can't access the nib in Interface Builder, find the constraint in code:
NSLayoutConstraint *heightConstraint;for (NSLayoutConstraint *constraint in myView.constraints) { if (constraint.firstAttribute == NSLayoutAttributeHeight) { heightConstraint = constraint; break; }}heightConstraint.constant = 100;
And in Swift:
if let constraint = (myView.constraints.filter{$0.firstAttribute == .width}.first) { constraint.constant = 100.0 }
To get a reference of your height constraints :Click + Ctrl in the constraint and drag and drop in your class file :
To update constraint value :
self.heightConstraint.constant = 300;[self.view updateConstraints];
A more flexible way using this swift extension:
extension UIView { func updateConstraint(attribute: NSLayoutAttribute, constant: CGFloat) -> Void { if let constraint = (self.constraints.filter{$0.firstAttribute == attribute}.first) { constraint.constant = constant self.layoutIfNeeded() } }}
How to use this view extension to update constant value of existing constraints:
// to update height constanttestView.updateConstraint(attribute: NSLayoutAttribute.height, constant: 20.0)// to update width constanttestView.updateConstraint(attribute: NSLayoutAttribute.width, constant: 20.0)