How to update constraint programmatically?

五迷三道 提交于 2019-12-23 02:36:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!