简体   繁体   English

iOS / Objective-C / Autolayout将四个图像水平居中

[英]IOS/Objective-C/Autolayout Center four images horizontally

I have been centering three images using autplayout quite easily. 我一直很容易地使用autplayout将三个图像居中。 I center the middle one horizontally, set all three to the same baseline and then set the leading and trailing spaces of the outside ones relative to the middle one. 我将中间的一个水平居中,将所有三个设置为相同的基线,然后相对于中间的一个设置外部空间的前导和尾随空间。

Now, however, I need to add a fourth image and therefore center an even number of images. 但是,现在,我需要添加第四个图像,并因此使偶数个图像居中。 So I can no longer use the same trick. 所以我不能再使用相同的把戏了。 I'd like to avoid adding more subviews but can't think of a simple way to do this. 我想避免添加更多的子视图,但是想不出一种简单的方法来做到这一点。

Can anyone recommend a preferred practice for centering an even number of horizontal images, horizontally? 谁能推荐一种首选的做法,将水平数量的偶数图像水平居中?

Here is what the three images look like. 这是三个图像的样子。 I want to add a fourth. 我要添加第四个。

在此处输入图片说明

Thanks n advance for any suggestions. 感谢您的任何建议。

I would suggest you use a stack view. 我建议您使用堆栈视图。 For your case you can have horizontal stack view with distribution set to fill equally. 对于您的情况,您可以使用水平堆栈视图,将分布设置为相等。 Set the constraints to your stackview according to your requirement and put your image views inside the stackview. 根据需要将约束设置到您的stackview并将图像视图放入stackview中。 When ever your want to adda new image you just have to drag it and it will adjust accordingly. 每当您要添加新图像时,只需拖动它,它就会相应地进行调整。

在此处输入图片说明

It will look like this 看起来像这样

在此处输入图片说明

If you add another then it will look like this. 如果添加另一个,它将看起来像这样。

在此处输入图片说明

You can read more on how to use stack-view in here 您可以在此处阅读有关如何使用堆栈视图的更多信息

Apple Documentation 苹果资料

Good tutorial to follow 好的教程

Use a UIStackView for jobs like these: 使用UIStackView进行以下工作:

let stackView = UIStackView()

stackView.distribution = .fill
stackView.alignment = .center
stackView.axis = .horizontal
stackView.spacing = 30 // or whatever you need

// now add the dots to your stackView:
stackView.addArrangedSubview(dot1)
stackView.addArrangedSubview(dot2)
stackView.addArrangedSubview(dot3)
stackView.addArrangedSubview(dot4)

// and just add and lay out the stackView, stackView itself will take care of positioning the dots
self.view.addSubview(stackView)
...

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

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