user6631314
user6631314

Reputation: 1970

IOS/Objective-C/Autolayout Center four images horizontally

I have been centering three images using autplayout quite easily. 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.

enter image description here

Thanks n advance for any suggestions.

Upvotes: 0

Views: 61

Answers (2)

Milan Nosáľ
Milan Nosáľ

Reputation: 19765

Use a UIStackView for jobs like these:

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

Upvotes: 2

Gihan
Gihan

Reputation: 2536

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. When ever your want to adda new image you just have to drag it and it will adjust accordingly.

enter image description here

It will look like this

enter image description here

If you add another then it will look like this.

enter image description here

You can read more on how to use stack-view in here

Apple Documentation

Good tutorial to follow

Upvotes: 2

Related Questions