【问题标题】:ios auto-layout: Programmatically set width constraintios自动布局:以编程方式设置宽度约束
【发布时间】:2013-06-23 10:33:52
【问题描述】:

我正在开发一个 ios 应用程序。我正在以编程方式将自动布局添加到 2 个标签。

我需要添加一个约束使它们的宽度相等。

我知道如何通过使用来固定标签的宽度:

constraint = [NSLayoutConstraint
    constraintWithItem:myLabel
             attribute:NSLayoutAttributeWidth
            relatedBy:NSLayoutRelationEqual
              toItem: nil
           attribute:NSLayoutAttributeNotAnAttribute
          multiplier:1.0f
            constant:200.0f];

这会将标签大小固定为常数。但是我有 2 个标签,我希望它们具有相同的大小,而不必设置常量。

【问题讨论】:

    标签: iphone ios constraints autolayout


    【解决方案1】:

    原来我只需要执行以下操作:

    constraint = [NSLayoutConstraint
        constraintWithItem:myLabel
            attribute:NSLayoutAttributeWidth
            relatedBy:NSLayoutRelationEqual
              toItem: otherLabel
           attribute:NSLayoutAttributeWidth
          multiplier:1.0f
            constant:0];
    

    【讨论】:

    • 为什么需要一个 toItem: otherLabel?
    • 这个想法是让“myLabel”和“otherLabel”等宽。所以我把其中一个放在“withItem”中,另一个放在“otherItem”中
    • 如果我只想为 myLabel 添加宽度约束怎么办?我会为“toItem”放什么。我试过 nil 但这并没有多大作用。谢谢
    • @VanDuTran 你必须把toItem: nil 并在常量中指定想要的大小。例如constant: 100。如果您遇到问题,您可以发布一个新的 SO 问题,您会得到答案。
    猜你喜欢
    • 2015-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多