xcode 将带有自动布局的 UIView 居中无法正常工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25866408/
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-09-15 05:34:42  来源:igfitidea点击:

Center a UIView with auto layout is just not working

iosobjective-cxcodestoryboard

提问by Curnelious

I have UIImageViewwhich is in the screen size (auto layoutsare 0 to all neighbours) . Inside it, i have another UIImageView., i would like it to always be in the Center of its parent imageview(hence on the Center of the screen) , and so it will change its size in relation to screen size, and keep aspect ratio .

我有UIImageView屏幕大小(auto layouts对所有邻居都是 0)。在它里面,我有另一个UIImageView.,我希望它总是在它的父级的中心imageview(因此在屏幕的中心),所以它会根据屏幕大小改变它的大小,并保持纵横比。

So inside the storyboard(Xcode 6), i am trying to control drag from the Center view to its parent, than i add aspect ratio constrain,than i see its aspect ratio,and that the constrain added.

所以在storyboard(Xcode 6)中,我试图控制从中心视图到其父视图的拖动,而不是我添加aspect ratio constrain,然后我看到它的纵横比,并添加了约束。

Running this now, will NOTchange image size and it stay in the same size for all screens.

现在运行它,不会改变图像大小,它在所有屏幕上都保持相同的大小。

Than in the same way , i want to Center it , so i control drag to its superview , than chose Center Xand Center Y, needless to say that its notcentred to any screen size.

以同样的方式,我想将它居中,所以我控制拖动到它的超级视图,而不是选择Center XCenter Y,不用说它居中到任何屏幕尺寸。

Why is it has to be so hard to place a view in the Center ?

为什么在中心放置一个视图如此困难?

回答by ullstrm

It's super easy. See my images:

这非常容易。看我的图片:

Then you need width/height-constraints:

然后你需要宽度/高度约束:

enter image description here

enter image description here

And you're done!

大功告成!

To replace your view in storyboard according to constraints, just select the view itself and use update frames:

要根据约束替换故事板中的视图,只需选择视图本身并使用更新框架:

enter image description here

enter image description here

Edit:

编辑:

If you want aspect-ratio width/height, just do this (The multiplier part): enter image description here

如果您想要纵横比宽度/高度,只需执行此操作(乘数部分): enter image description here







EDIT 2:

编辑2:

Clarification of how to open the first window. Then just press the checkboxes to add the constraints:

说明如何打开第一个窗口。然后只需按下复选框即可添加约束:

enter image description here

enter image description here

These "center in container"-constraints should be the same as the added ones in this window (CTRL-drag to superview to open this): enter image description here

这些“容器中的中心”-约束应该与此窗口中添加的约束相同(CTRL-拖动到超级视图以打开它): enter image description here

EDIT 3:

编辑 3:

To clarify what button to press:

澄清按下哪个按钮:

enter image description here

enter image description here