Search code examples
iosxcodeautolayout

autolayout - make height of view relative to half superview height


have been getting into autolayouts recently and I'm stuck on what seems like a really trivial problem example. I have a view that I want to sit at the top of the screen, and take up half of the screen-height. Simple before autolayout - just tack it in place and tell it to expand vertically when the superview resizes.

Now, I can't for the life of me see how to do it. Here's what I get when I try to set this up:

autolayout blues

The bottom space constraint is set to "equals 284", which is absolute and absolutely useless to me when I change to iPhone4 layout, as it keeps 284 points space at the bottom of the screen, and shrinks the view to no longer be half the size of the screen. And there's no way of setting that constraint to equal some fraction of any other view's height..

After struggling for a while, the only way I can think of doing this would be to introduce another view below this view, pin their heights equally, have them sit above and below each other and then set the second (bottom) view to be invisible.. which seems a bit ugly!

Am I missing something obvious?..


Solution

  • This is now possible in IB as of [at least] Xcode 5.1.1. Although it took me sometime to figure out it is actually super simple:

    First create a basic top alignment constraint (you will also need to setup bottom, left, and right constraints, like normal) . Then select the constraint and navigate to the Attribute inspector:

    Demonstration of steps above

    Then you can adjust the multiplier. If you want it 50% of the super view leave it at 1, since it is aligned per the super's center. This is also a great way to create views that are other percentages too (like 25% of super view)

    Demonstration of second step above