剩余空间中的自动布局居中视图(以编程方式) [英] Auto Layout centering view in remaining space (programmatically)

查看:113
本文介绍了剩余空间中的自动布局居中视图(以编程方式)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何添加自动布局约束以编程方式将视图置于剩余空间的中心(参见下面的示例图片)?

How can add Auto Layout constraints programmatically to center a view in the remaining space (see example picture below)?

目前,我添加了一个容器在底部查看,然后我将视图置于容器视图中心,但我想知道是否有任何其他解决方案而无需使用容器视图。

For the moment, I add a container view at the bottom and I then center the view in the container view, but I was wondering if there was any other solution without needing to use a container view.

推荐答案

你需要添加一个间隔视图来做这件事。

You need to add a spacer view to do this.

让我们从一些观点开始:

Let's start with some views:

我' ll设置粉红色视图占据根视图的前70%。首先,我将它固定到根视图的所有四个边缘:

I'll set up the pink view to take up the top 70% of the root view. First I pin it to all four edges of the root view:

然后我将以两种方式编辑底部约束。首先,我确保第一项是粉红色视图,然后我设置乘数为0.7。然后我更新粉红色视图的框架:

Then I'll edit the bottom constraint in two ways. First, I make sure the first item is the pink view, and second I set the multiplier of 0.7. Then I update the pink view's frame:

接下来我将添加间隔视图。我不希望间隔视图在运行时可见,所以我会隐藏它。隐藏的视图仍然参与布局。在设置约束之前,我只是将间隔符放在蓝色视图的左侧:

Next I'll add the spacer view. I don't want the spacer view to be visible at runtime, so I'll make it hidden. Hidden views still participate in layout. Before setting up constraints, I just put the spacer to the left of the blue view:

现在我将创建约束以使间隔从粉红色视图的底部延伸到根部的底部视图。宽度无关紧要,所以我只需将它固定在超视图的左边缘并使其变薄:

Now I'll create constraints to make the spacer stretch from the bottom of the pink view to the bottom of the root view. The width doesn't matter so I'll just pin it to the left edge of the superview and make it thin:

现在我已准备好设置蓝色视图。首先我会给它一个固定的大小:

Now I'm ready to set up the blue view. First I'll give it a fixed size:

其次我将它水平放在根视图中:

Second I'll center it horizontally in the root view:

第三,我将其垂直中心固定在spacer的垂直中心:

Third I'll pin its vertical center to the spacer's vertical center:

这就是我需要的所有限制。我将更新所有帧以进行检查:

That's all the constraints I need. I'll update all frames to check:

我可以使用助理编辑器中的预览来测试它:

I can test it out using Preview in the assistant editor:

请注意,在预览中看不到间隔视图,但仍然参与布局。

Notice that the spacer view isn't visible in the preview, but still participates in layout.

这篇关于剩余空间中的自动布局居中视图(以编程方式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆