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
iOS: Programmatically change height constraint of a UIView
提问by Marcus
I wonder is there a way to programmatically retrieve the height constraint of a specific UIView
and change its value in the code? I have a situation where I have several UIViews
with 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 UIViews
and cause some UIViews
to be pushed downward in the view.
我想知道有没有办法以编程方式检索特定的高度约束UIView
并在代码中更改其值?我有一个情况,我有几个UIViews
在 IB 中固定了四个边并添加了高度限制(如果我没有,IB 会抱怨),但是在程序中间我需要更改 的高度UIViews
并导致一些UIViews
被推在视图中向下。
I know I can ctrl+dragthe height constraints of each UIViews
and 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 .h
file:
首先向您的.h
文件添加高度约束:
//Add Outlet
IBOutlet NSLayoutConstraint *ViewHeightConstraint;
Next, add the below code to your .m
file:
接下来,将以下代码添加到您的.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
您可以将该特定约束连接到来自界面构建器的代码,例如
And NSLayoutConstraint
has 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 NSLayoutConstraint
class. 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?
}