iOS autolayout to center my view between two views

IosInterface BuilderAutolayout

Ios Problem Overview


How to set up autolayout in Interface Builder to arrange views vertically as shown on image:

scheme

Top view pinned to top screen edge, Bottom view pinned to bottom screen edge. My view should be centered between top and bottom views (so distance to Top view equals to distance to Bottom view)

Ios Solutions


Solution 1 - Ios

The way to do this is to have 2 invisible "spacer" views between you visible views.

You can't make spaces have equal height. But you use the "spacer" views and place them between your views (with 0 gap to the surrounding views).

Then you give these views equal heights and they will push your views around to centre the My View with equal gap to the Bottom View and Top View.

i.e. like this...

V:|[Top View][spacer1][My View][spacer2(==spacer1)][Bottom View]|

EDIT - Another way

I just thought of another way of doing this. You could have an invisible container UIView that is between Top View and Bottom View with no gap.

Then you place My View inside this invisible view and centre it vertically.

Solution 2 - Ios

One more solution is to add an invisible view between top view and botom view and place my view in center of this view:

Centered UIView

Solution 3 - Ios

(5 years later) I've found the most canonical solution:

UILayoutGuide is specially introduced to solve this kind of tasks (since iOS 9).

Use layout guides to replace the dummy views you may have created to represent inter-view spaces or encapsulation in your user interface - Ref docs

It works pretty fine in code, but unfortunately Interface Builder doesn't support custom layout guides.

Solution 4 - Ios

This video gives an amazing overview of auto layout and constraints in interface builder: https://www.youtube.com/watch?v=1j-Frd5snYc

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbrigadirView Question on Stackoverflow
Solution 1 - IosFogmeisterView Answer on Stackoverflow
Solution 2 - Iosanatoliy_vView Answer on Stackoverflow
Solution 3 - IosbrigadirView Answer on Stackoverflow
Solution 4 - Iosuser3474985View Answer on Stackoverflow