如何以编程方式更新约束? [英] How to update constraints programmatically?
问题描述
我想以编程方式在代码中更新约束.我已将它们添加到情节提要控制器中.我为约束创建了 IBOutlet
并将其连接起来.我在 updateViewConstrains()
中添加了值,但是它不起作用:
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 in updateViewConstrains()
but it isn't working:
func updateViewConstraints() {
centerYConstraint.constant = 60
super.updateViewConstraints()
}
推荐答案
在您的 viewController.h
文件中创建一个 IBOutlet
:
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];
以下摘录自此文章
如果由于上述约束的更新而其他约束将受到影响,则还必须调用以下约束:
If other constraints will be affected because of the update to the constraint above, the following must also be called:
[viewForUpdate setNeedsUpdateConstraints];
现在,通过在动画块内调用 layoutIfNeeded
为您的视图添加动画.
Now, animate yout view by calling layoutIfNeeded
inside your animation block.
这篇关于如何以编程方式更新约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!