How to update constraints programmatically?
Solution 1
create an IBOutlet
in your viewController.h
file :
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *nameButtonVerticalConstraint;
now connect it with the concerned autolayout constraint :
Now you can simply change the constraint like this :
self.nameButtonVerticalConstraint.constant=25;
And if you want smoother transitions, you can put it inside an animation block :
[UIView animateWithDuration:1.2 delay:1 options:UIViewAnimationOptionCurveEaseInOut animations:^{
self.nameButtonVerticalConstraint.constant=50;
[self.view layoutIfNeeded];
} completion:nil];
EDIT : here's an excerpt from this article
If other constraints will be affected because of the update to the constraint above, the following must also be called:
[viewForUpdate setNeedsUpdateConstraints];
Now, animate yout view by calling layoutIfNeeded
inside your animation block.
Solution 2
Try myConstraintOutlet.constant = newValue;
Solution 3
You can update the constant
property of the layout constraint.
Related videos on Youtube
Nik
Updated on June 04, 2022Comments
-
Nik almost 2 years
I want to update constraints programmatically in code. I have added them in storyboard controller. I made
IBOutlet
for the constraints and connected them. I added values inupdateViewConstrains()
but it isn't working:func updateViewConstraints() { centerYConstraint.constant = 60 super.updateViewConstraints() }
-
Wain almost 9 yearsShow your code, what specifically doesn't work?
-
Nik almost 9 yearsoverride func updateViewConstraints() { centerYConstraint.constant = 60 super.updateViewConstraints() }
-