iOS 自动布局将我的视图集中在两个视图之间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21024759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 23:03:43  来源:igfitidea点击:

iOS autolayout to center my view between two views

iosinterface-builderautolayout

提问by brigadir

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

如何在 Interface Builder 中设置自动布局以垂直排列视图,如图所示:

scheme

方案

Top viewpinned to top screen edge, Bottom viewpinned to bottom screen edge. My viewshould be centered between top and bottom views (so distance to Top viewequals to distance to Bottom view)

Top view固定到屏幕顶部边缘,Bottom view固定到屏幕底部边缘。My view应该在顶视图和底视图之间居中(因此距离 toTop view等于距离 to Bottom view

回答by Fogmeister

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

这样做的方法是在可见视图之间有 2 个不可见的“间隔”视图。

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

你不能让空间具有相同的高度。但是您使用“间隔”视图并将它们放置在您的视图之间(与周围视图的间隙为 0)。

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

然后你给这些观点相等的高度,他们将围绕推动你的看法居中My View等于差距的Bottom ViewTop 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 UIViewthat is between Top Viewand Bottom Viewwith no gap.

我只是想到了另一种方法来做到这一点。你可以有一个无形的容器UIView是之间Top ViewBottom View没有差距。

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

然后你把它My View放在这个不可见的视图中并垂直居中。

回答by anatoliy_v

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

另一种解决方案是在顶视图底视图之间添加一个不可见的视图,并将我的视图放在此视图的中心:

Centered UIView

居中的 UIView

回答by brigadir

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

(5 年后)我找到了最规范的解决方案:

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

UILayoutGuide专门用于解决此类任务(自 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.

它在代码中工作得很好,但不幸的是 Interface Builder 不支持自定义布局指南。

回答by user3474985

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

该视频提供了界面构建器中自动布局和约束的惊人概述:https: //www.youtube.com/watch?v=1j-Frd5snYc