Search code examples
iosxcodeautolayoutinterface-builder

Creating grid with one big square using auto layout


Please advise on how should I approach implementing the following layout using Xcode's Auto Layout?

The idea here is that redView and all blueViews are all perfect squares with equal spacing.

I was only able to create working version with the redView and 2 vertical blueView without the bottom 3 blueViews.

auto layout grid issue


Solution

  • enter image description here


    Here is how I would approach it.

    1. First create the big yellow square. Give it an aspect ratio of 1:1. Add a constraint to center it horizontally in the view. Give it leading edge and top edge constraints.
    2. Add view B. Give it an aspect ratio of 1:1. Align it with the top edge and trailing edge of the yellow square.
    3. Add view C. Align it to the trailing edge of yellow and center it vertically in yellow. Add equal width and equal constraints to view B. Give it a vertical space of 16 from view B.
    4. Add view F. Align it to the trailing edge and bottom edge of yellow. Give it equal width and height of view C.
    5. Add view E. Align it to the bottom edge of yellow. Center it horizontally in yellow. Give it equal width and height to F.
    6. Add view D. Align it to the leading edge and bottom edge of yellow. Give it equal width and height to E.
    7. Add view A. Give it aspect 1:1. Align it to leading edge of yellow and top edge of yellow. Align its bottom edge with bottom edge of C.
    8. Change background color of yellow to clear.

    That will do it. The yellow square will resize for all devices, and the red and blue squares will be sized accordingly. You can change the distance constraint between views B and C and all gaps will adjust automatically, which makes this easy to adjust for the desired look.


    Here is an example running in the simulator. I hooked up the slider to change the value of the constant for the constraint setting the distance between views B and C.

    enter image description here