Joseph Lin
Joseph Lin

Reputation: 3334

Auto-Layout Constraint: When resizing, distributes the space non-equally to the subviews?

It might be easiest to demonstrate my question with an example, so here it goes:

I have a container view, which has two subviews, A and B.

Container: 240x80

A: 80x80, pinned leading/top/bottom spacing.

B: 160x80, pinned leading/top/bottom spacing, pinned h spacing with A.

enter image description here

Now, when I resize the container to, say, 480x80, I got something like this: enter image description here

That is because Xcode thinks my constrains are ambiguous, so it pinned A's width for me and gives all additional horizontal space to B.

Ok, I understand its concern, but what I really want is to have both A and B resize proportionally, like this:

enter image description here

My hunch is that it'll have something to do with the Hugging/Compression Resistance Priority settings, but I can't figure out how to set those values to get the results I want!

To put this question in an other way, when the container is enlarged, how do I specify where the extra space go? How do I set the priorities so that the space distributes to view A and view B 4:6? 5:5? 8:2?

Thanks!

Upvotes: 4

Views: 2844

Answers (2)

Aaron
Aaron

Reputation: 7145

Not that the provided answer is unworthy but you should be able to do this now in Xcode (5.1.1) by creating an equal width constraint between view A and view B and setting a multiplier.

To do that, remove any other width constraints you might have between these two views then control drag from view A to view B and choose an Equal Widths constraint. Select that constraint from the Document Outline view and then in the inspector, change the Multiplier to the ratio you want. In your case it looks like it might be 1:3, or something close that. Here's what my view might look like:

enter image description here

And what the inspector should look like:

enter image description here

Just play with the ratios, until you get it right.

Upvotes: 4

rdelmar
rdelmar

Reputation: 104082

This is very similar to the other question you just asked. Make a constraint that makes the width of one view equal to the other with a multiplier to get the ratio you want:

NSLayoutConstraint *con = [NSLayoutConstraint constraintWithItem:self.viewA attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.viewB attribute:NSLayoutAttributeWidth multiplier:0.5 constant:0];

This constraint need to be added to the superview of views A and B.

Upvotes: 6

Related Questions