Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Subview's Width Porportional to Superview's

I am trying to set a constraint that would look like this (subview in red superview in white):

How would I do this in interface builder (preferably) and if not possible then code, but what should I put as the width to make IB happy?

I have tried selecting the subview and superview, but it won't let me set constraints that way.

like image 620
carloabelli Avatar asked Jan 10 '23 04:01

carloabelli


1 Answers

You can do it entirely in IB. I don't know what you mean by "I have tried selecting the subview and superview, but it won't let me set constraints that way"; that, indeed, is exactly what you must do, and exactly what it will let you do — in short, that is precisely how you do a relationship of that sort.

I'll describe the whole thing in three stages. Start with your subview and draw out the initial constraints for top, left, and right:

enter image description here

Now select the view and its superview and use the popup at the bottom to set equal widths (of course when you are finished they will not be equal, but this is just to form the constraint itself):

enter image description here

Finally, fix all the constraint values by selecting each one in turn and editing its Constant in the attributes inspector. The values will all need to be 0, except for the widths relationship, of course; there, you'll enter the two values that you gave in your question:

enter image description here

You're now finished, but if you want the "misaligned" warnings to go away, choose Update All Frames to make the layout look the way it will at runtime. Or just run it and see what you've got!

EDIT: In a .xib, you won't be able to form the width = width constraint to the top-level view. To get around this, use an invisible intervening "container view" to act as a buffer between the top-level view and everything else. Pin the container view with zero values on all sides to the top-level view; now the container view will act as the container for everything else, and you'll be able to pin in terms of its width:

enter image description here

like image 63
matt Avatar answered Jan 21 '23 08:01

matt