Search code examples
iosiphoneswiftautolayoutxcode6.1

Autolayout Shrink and Expand with phone size


I'm having a tough time getting my app to size with auto layout. I've watched just about every tutorial and messed with it for days using constraints, classes but it just isn't perfect.

I've attached a mockup of what I'm trying to do. I've created restraints but when it shrinks down one row is just smaller than the rest so it fits. If I added an equal height constraint then everything just gets pushed up in the header. I'm not using a table view, just text and the lines as images.

I'm basically just trying to keep the same ration but have the rows shrink to fit between the header and footer using a regular view.

Thanks for any help.

example mockup


Solution

  • I've just put together a layout that does what you want, if I'm understanding you correctly. Here's how it looks in the iPhone 4S, 5S and 6:

    iPhones

    The views I used are:

    • UIView for Header
    • UIView with a UILabel inside for each of "One", "Two", "Three", "Four".
    • UIView with a dark grey background colour and a height constraint of 1 for the bottom borders of "One", "Two", Three" and "Four".

    There are two important sets of constraints to get the "stretchiness":

    • Equal Height constraints between "One" and each of Header, "Two", "Three", and "Four". I used a multiplier of 0.5 on the equal height constraint between "One" and "Header" because it looks to me like your header is about twice as high as each of the rows.
    • Vertical Space constraints of 0 (a) between the Top Layout Guide and Header, and (b) between the bottom "border" view of "Four" and the Bottom Layout Guide.

    Basically, as long as you pin the top view to the top of the screen, the bottom view to the bottom of the screen, and give enough equal width constraints to relate all the views to each other in terms of height, Auto Layout will just figure out the actual heights for you. The only views I put any specific height constraints on (i.e. with an actual number) are the 1-pixel high views that act as the "bottom border" lines.

    There's lots of other constraints going on, but they're basically pretty obvious—everything has leading and trailing space of zero to the container, zero vertical space constraints between each item and the next going down vertically. The number labels inside the views are pinned to the left-hand edge and centred vertically in their container.

    It was a bit of a fiddle and Xcode crashed a couple of times, but that, sadly, is Auto Layout for you. Save early, save often.