Eric
Eric

Reputation: 16931

Auto Layout - make a view's dimensions dependent on another view's

Simple deal: I'd like to make a UIView's width half of its superview's width. Here's my code:

//Display a red rectangle:
UIView *redBox = [[UIView alloc] init];
[redBox setBackgroundColor:[UIColor redColor]];
[redBox setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.view addSubview:redBox];

//Make its height equal to its superview's,
//minus standard spacing on top and bottom:
NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[redBox]-|" options:0 metrics:nil views:@{@"redBox": redBox}];
[self.view addConstraints:constraints];

//Make its width half of its superviews's width (the problem):
NSLayoutConstraint *constraint = [NSLayoutConstraint
                                  constraintWithItem:redBox
                                  attribute:NSLayoutAttributeWidth
                                  relatedBy:NSLayoutRelationEqual
                                  toItem:self.view
                                  attribute:NSLayoutAttributeWidth
                                  multiplier:0.5
                                  constant:0.0
                                  ];

[self.view addConstraint:constraint];

[self.view setBackgroundColor:[UIColor blueColor]];

This is what I get:

enter image description here

If I set multiplier to 1.0, then the view's width is half of its superview. But why is that?

Upvotes: 1

Views: 355

Answers (1)

BJ Homer
BJ Homer

Reputation: 49054

The problem is probably that your red box view is under-constrained. You've given it a width, but nothing to tell it where it should position itself horizontally. Since it should be half the width of the superview, it could choose to position itself on the left half of the superview. Or the right half. Or the middle. You didn't specify, so the framework just gets to pick something.

In this case, it looks like it's choosing to align the center of the red box with the left edge of the superview. This seems like an odd choice, but again, you didn't specify anything. It can pick whatever it wants.

Add another constraint that will position the view horizontally. That should fix the problem.

Upvotes: 1

Related Questions