IOS 自动布局使我的视图在两个视图之间居中

如何设定 Interface Builder 的自动布局,以垂直排列图片所示的视图:

scheme

Top view固定在屏幕顶部边缘,Bottom view固定在屏幕底部边缘。My view应该在顶部和底部视图之间居中(所以到 Top view的距离等于到 Bottom view的距离)

24917 次浏览

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.

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

(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.