UIStackView not centering arrangedview

2.3k views Asked by At

I am implementing a UIStackView and populating a UIStackView dynamically. But when there is a single view in UIStackView, the view is not centred in the UIStackView.

I use horizontal axis, center alignment and fill equality distribution in UIStackView. How can I start to populate UIStackView by putting views in center of the UIStackView?

Current behaviour of UIStackView

enter image description here

I want to start adding stars in the center of the UIStackView enter image description here

I am new to UIStackView sorry for an easy question.

I'm adding arranged views like;

tmpView = [[UIView alloc] init];
tmpImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"iconStar"]];
[tmpView addSubview:tmpImageView];

[self.horizontalStackView addArrangedSubview:tmpView];

How can I achieve desired behaviour?

1

There are 1 answers

8
Fogmeister On

OK, it is as I thought. When you set the alignment of a UIStackView this works perpendicular to the axis of the stack view.

So in your case, the center means it will center the items from top-to-bottom (which it is doing).

In the direction of the axis the stack view will fill up from the top (in a vertical axis) or from the left (in a horizontal axis).

If you want your image to be centered like in your second screen shot then you could change the axis to .vertical and it would work. Without knowing what your end goal is I can't really recommend a specific solution.

If all you want is to align the single image this way then this should be fine.