iOS:以编程方式更改 UIView 的高度约束

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28293892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 04:38:40  来源:igfitidea点击:

iOS: Programmatically change height constraint of a UIView

iosiphonexcode-storyboard

提问by Marcus

I wonder is there a way to programmatically retrieve the height constraint of a specific UIViewand change its value in the code? I have a situation where I have several UIViewswith four edges pinned in the IB and height constraints added (IB complains if I did not), but in the middle of the program I would need to change the height of the UIViewsand cause some UIViewsto be pushed downward in the view.

我想知道有没有办法以编程方式检索特定的高度约束UIView并在代码中更改其值?我有一个情况,我有几个UIViews在 IB 中固定了四个边并添加了高度限制(如果我没有,IB 会抱怨),但是在程序中间我需要更改 的高度UIViews并导致一些UIViews被推在视图中向下。

I know I can ctrl+dragthe height constraints of each UIViewsand change their values in the code, but doing so would require me to wire dozens of them. So I think this is not efficient and not scalable in some way.

我知道我可以按ctrl+拖动每个的高度约束UIViews并在代码中更改它们的值,但这样做需要我连接几十个。所以我认为这在某种程度上效率不高且不可扩展。

So I wonder is there a way to totally retrieve the height constraints of a specific view through code and change it dynamically?

所以我想知道有没有办法通过代码完全检索特定视图的高度约束并动态更改它?

Thanks!

谢谢!

回答by Bhavin Chauhan

First add height constraint to your .hfile:

首先向您的.h文件添加高度约束:

//Add Outlet     
IBOutlet NSLayoutConstraint *ViewHeightConstraint;

Next, add the below code to your .mfile:

接下来,将以下代码添加到您的.m文件中:

//Set Value From Here   
ViewHeightConstraint.constant = 100;

回答by Ashraf Tawfeeq

You can connect that specific constraint to your code from the interface builder like

您可以将该特定约束连接到来自界面构建器的代码,例如

enter image description here

在此处输入图片说明

And NSLayoutConstrainthas a constant property to be set which is your constant pin value.

并且NSLayoutConstraint有一个常量属性要设置,它是你的常量引脚值。

If you're adding your constraints programmatically, you can surely benefit from the identifier property in NSLayoutConstraintclass. Set them and iterate over them to get that specific identifired constraint.

如果您以编程方式添加约束,您肯定可以从NSLayoutConstraint类中的 identifier 属性中受益。设置它们并迭代它们以获得特定的识别约束。

As the documentation says

正如文档所说

extension NSLayoutConstraint {
    /* For ease in debugging, name a constraint by setting its identifier, which will be printed in the constraint's description.
     Identifiers starting with UI and NS are reserved by the system.
     */
    @availability(iOS, introduced=7.0)
    var identifier: String?
}