Search code examples
xcodeautolayout

How do constraints and autolayout work in Storyboards? Xcode 9


I've watched several videos and read docs on how to use constraints and autolayout for my app.

I'm trying to make my design universal on all screen sizes.

The problem is, no matter what I do, my designs go all over the place and I have no idea why.

Example: I'll have a title that's supposed to be dead in the center of a screen, a set y-axis, and I'll turn aspect ratio on (or off - both don't work).

If the title is 100px from the left side and 100px from the right side, I'll add those constraints, and add Y axis constraints. I'll turn on aspect ratio, but have tried with it off. For the most part Y axis constraints work fine.

The title looks perfect in the default design I added constraints in, but if I run it in a different phone size, the title shoots 30 - 40% over to the left. I can't get any design to stick to the constraints.

I'm able to get a background image to work perfectly but other assets aren't working for me. It's getting pretty frustrating and I feel like I'm missing something obvious but nothing I find is giving me that missing link.

To sum it up: I've watched videos/read documentation on constraints and autolayout in storyboards for Xcode 9 but the moment I load up a different screen size my designs go haywire and don't stick to the constraints.

What am I missing here?


Solution

  • Whenever you are working with constraints, always remember to specify these things:

    • x coordinate
    • y coordinate
    • height
    • width

    If you specified all those things unambiguously, it will work. It's simple as that.

    I'll have a title that's supposed to be dead in the center of a screen, a set y-axis

    By saying that, you have specified the x and y coordinates of the title. Good! Now you need to think about its size. How do you want its size to change? Here are some possibilities:

    Size is constant:

    enter image description here

    Constant distance between left edge and left edge of screen, right edge and right edge of screen:

    enter image description here

    Width is half of screen width, height is half of screen height:

    enter image description here

    This last case can be a little tricky to do. You can add these kind of constraints by first adding an aspect ratio constraint, then setting different things in the property inspector:

    enter image description here