Search code examples
iosxcode6autolayoutinterface-builderxcode-storyboard

Weird behaviour with constraints to top / bottom layout guide


I've god a storyboard (Xcode 6.4) with a view controller and two subviews arranged vertically over each other. Picture like a Facebook timeline screen in their app, only with just two tiles.

  • The first view is constrained to the top layout guide, and to the top of the second view below it (distances 8 or whatever).
  • The second view is constrained to the bottom of the first view, and to the bottom layout guide (distances 8 or whatever).
  • Other horizontal constraints that are not relevant.
  • Bottom line - everything is blue and looks great when changing screen types inside storyboard.

While you're expecting the views to be flexible in height and simply scale vertically to fill the whole superview's height, when you run it, something goes wrong.

When running (with simulator or device), on different screens and devices (and iOS versions), you get weird unexpected behaviour near the layout guides, for example a margin shows up between a subview and the relevant top/bottom layout guide.

From what I searched, it looks like an Xcode bug, as I created a clean new project with only these constraints and it still got messed up.


Solution

  • So I found a hint here:

    https://www.youtube.com/watch?v=lxc9DnqpI0c

    And anyway the trick is to NOT constraint a subview to the top / bottom layout guides, but rather to the superview.

    Basically if you want to set a constraint between a subview (not the main view) to the top / bottom of the screen, do not use the usual ctrl+drag technique, but just select it and then go:

    Editor > Pin > Top Space to Superview

    Spent some few hours on this!