简体   繁体   中英

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.

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM