问题
I want to update constraint programmatically in code. I have added them in storyboard controller. I make IBOutlet for the constraint and connect them. I add values in updateViewConstrains()
but it isn't working:
func updateViewConstraints() {
centerYConstraint.constant = 60
super.updateViewConstraints()
}
回答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.
回答2:
Try myConstraintOutlet.constant = newValue;
回答3:
You can update the constant
property of the layout constraint.
来源:https://stackoverflow.com/questions/29470996/how-to-update-constraint-programmatically