Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ios auto-layout: Programmatically set width constraint

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.

like image 689
Y2theZ Avatar asked Jun 26 '13 10:06

Y2theZ


People also ask

What is NSLayoutConstraint?

An NSLayoutConstraint specifies the relationship between two layout attributes (FirstAttribute and SecondAttribute, both of which are of type NSLayoutAttribute) in a constraint-based layout. The relationship consists of: A NSLayoutRelation (e.g., GreaterThanOrEqual)

What are two properties that auto layout constraints control on a UIView?

Auto Layout defines margins for each view. These margins describe the preferred spacing between the edge of the view and its subviews. You can access the view's margins using either the layoutMargins or layoutMarginsGuide property.


1 Answers

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];
like image 157
Y2theZ Avatar answered Oct 09 '22 04:10

Y2theZ