如何以编程方式更改从故事板添加的约束?

Nil*_*ari 22 objective-c ios xcode-storyboard

我有一个屏幕.它将显示如下

在此输入图像描述

现在当用户点击我有一个帐户和密码(按钮)时,它将显示如下

在此输入图像描述

我想相应地移动两个视图我使用storyboard添加了约束.现在需要从编程中改变约束.

Car*_*Zyl 45

您需要创建约束的IBOutlet.
在此输入图像描述

然后在代码中设置约束的常量值:

labelWidthConstraint.constant = newValue
Run Code Online (Sandbox Code Playgroud)

如果你想要它的动画,你可以做这样的事情:

迅速

labelWidthConstraint.constant = newValue
UIView.animate(withDuration: 0.3, animations: { 
    self.view.layoutIfNeeded()
})
Run Code Online (Sandbox Code Playgroud)

Objective-C的

self.labelWidthConstraint.constant = newValue;
[UIView animateWithDuration:0.3 animations:^{        
    [self.view layoutIfNeeded];
}];
Run Code Online (Sandbox Code Playgroud)

  • 你不应该调用`layoutSubviews()`(见文档)。改用`layoutIfNeeded()`。 (2认同)