19

I am working on an ios application. I am adding the auto-layout programmatically to 2 labels.

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.

1 Answer 1

16

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];
Sign up to request clarification or add additional context in comments.

4 Comments

why do you need a toItem: otherLabel?
the idea is to make the "myLabel" and "otherLabel" equal width. so I put one of them in the "withItem" and the other in the "otherItem"
what if I just want to add a width constrains to myLabel only? what would I put for "toItem". I tried nil but that doesn't do much. Thanks
@VanDuTran you have to put the toItem: nil and specify the wanted size in the constant. example constant: 100 . if you are having problems you can post a new SO question and you will get answers for it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.