如何以编程方式更新约束? [英] How to update constraint programmatically?

查看:90
本文介绍了如何以编程方式更新约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以编程方式在代码中更新约束.我已将它们添加到情节提要控制器中.我为约束创建IBOutlet并将其连接.我在updateViewConstrains()中添加了值,但是它不起作用:

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()
}

推荐答案

在您的viewController.h文件中创建IBOutlet:

@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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆