简体   繁体   English

剩余空间中的自动布局居中视图(以编程方式)

[英]Auto Layout centering view in remaining space (programmatically)

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:让我们从一些观点开始:

一些观点

I'll set up the pink view to take up the top 70% of the root view.我将设置粉红色视图以占据根视图的前 70%。 First I pin it to all four edges of the root view:首先,我将它固定到根视图的所有四个边缘:

粉色约束

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.首先,我确保第一项是粉红色视图,然后我将乘数设置为 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:其次,我将在根视图中将其水平居中:

蓝色水平中心

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.请注意,间隔视图在预览中不可见,但仍参与布局。

The accepted answer doesn't address the programmatic alternative (which you emphasized in your question).接受的答案没有解决程序化的替代方案(您在问题中强调了这一点)。

There is a programmatic way to do this without having to add additional dummy views to the view hierarchy using UILayoutGuide which was introduced in iOS 9.有一种编程方式可以做到这一点,而无需使用 iOS 9 中引入的UILayoutGuide向视图层次结构添加额外的虚拟视图。

The documentation for UILayoutGuide is detailed enough. UILayoutGuide的文档已经足够详细了。

This article also add more explanation ( Here is the updated code from the article). 这篇文章还添加了更多的解释( 是文章的更新代码)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM