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.
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:
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):
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:
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With