Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 623
Joseph Lin Avatar asked Dec 27 '22 11:12

Joseph Lin


1 Answers

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.

like image 191
rdelmar Avatar answered Feb 23 '23 00:02

rdelmar