ios 自动布局:以编程方式设置宽度约束
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17317495/
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 auto-layout: Programmatically set width constraint
提问by Youssef
I am working on an ios application. I am adding the auto-layout programmatically to 2 labels.
我正在开发一个 ios 应用程序。我正在以编程方式将自动布局添加到 2 个标签。
I need to add a constraint to make them equal width.
我需要添加一个约束,使它们的宽度相等。
I know how to fix the width of a label by using :
我知道如何使用以下方法修复标签的宽度:
constraint = [NSLayoutConstraint
constraintWithItem:myLabel
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem: nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.0f
constant:200.0f];
That would fix the label size to a constant. But I have 2 labels and I want them to have equal size without having to set a constant.
这会将标签大小固定为常量。但是我有 2 个标签,我希望它们具有相同的大小而不必设置常量。
采纳答案by Youssef
It turned out I just have to do the following:
事实证明,我只需要执行以下操作:
constraint = [NSLayoutConstraint
constraintWithItem:myLabel
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem: otherLabel
attribute:NSLayoutAttributeWidth
multiplier:1.0f
constant:0];