16

I have a label and button in a superView like this.

|--------------[Label]-----[button]-|

I'd like the label to be centred if possible, then have a min gap to the button and move to the left.

So if the button is big it looks like...

|-[        LABEL!        ]-[button]-|

So, the button stays where it is and at the same size. And there are minimum gaps between the elements.

I can add the centerX constraint but I can't seem to give it a priority so it remains Required.

How can I create this situation? I'm doing all the auto layout in code.

The constraints I currently have are...

[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-[_label]-(>=8@1000)-[_button(==45)]-|"
                                                             options:NSLayoutFormatAlignAllCenterY
                                                             metrics:nil
                                                               views:views]];

[self addConstraint:[NSLayoutConstraint constraintWithItem:_label
                                                 attribute:NSLayoutAttributeCenterX
                                                 relatedBy:NSLayoutRelationEqual
                                                    toItem:self.contentView
                                                 attribute:NSLayoutAttributeCenterX
                                                multiplier:1.0
                                                  constant:0.0]];

But I'm not sure how to reduce the priority of the second constraint.

Fogmeister
  • 76,236
  • 42
  • 207
  • 306

1 Answers1

36

You just set the priority property of the constraint, like so:

NSLayoutConstraint *centeringConstraint = 
    [NSLayoutConstraint constraintWithItem:_label
                                 attribute:NSLayoutAttributeCenterX
                                 relatedBy:NSLayoutRelationEqual
                                    toItem:self.contentView
                                 attribute:NSLayoutAttributeCenterX
                                multiplier:1.0
                                  constant:0.0];

centeringConstraint.priority = 800; // <-- this line

[self addConstraint:centeringConstraint];
BJ Homer
  • 48,806
  • 11
  • 116
  • 129
  • Of course! Thanks! I didn't think to create the object before adding it. Perfect! Got it sorted now, thanks! – Fogmeister Mar 12 '13 at 15:35