Kevin2566
Kevin2566

Reputation: 441

How to set custom heights on arranged subviews within a UIStackView?

I have a horizontal UIStackView with some arranged subviews, whose heights should be less than that of the StackView but centered along the StackView's y axis. However, even after setting constraints on the subviews, their height does not change and is equal to that of the StackView.

Apart from setting constraints defining the subviews' heights and setting their y axis to that of the UIStackView, I've set the StackView's alignment to center, and its distribution to "fill proportionally" - these have all been recommended in answers to similar questions, but none of them change the subviews' height.

I've also tried setting the StackView's directionalLayoutMargins, which both the top and bottom margins set to (height of the StackView - height of the arranged subviews) / 2, and all this does is shift the subviews far below the StackView's center y axis and, if I set the bottom margin to 0, squish the subviews.

Here are my constraints:

button.widthAnchor.constraint(equalToConstant: width),
button.heightAnchor.constraint(equalToConstant: 32),
button.centerYAnchor.constraint(equalTo: contentView.stackView.centerYAnchor)

Upvotes: 1

Views: 1895

Answers (1)

jake
jake

Reputation: 1264

A few things:

First, make sure you set:

button.translatesAutoresizingMaskIntoConstraints = false

Also, make sure your constraints are active, like so (this may already be the case but just being sure):

button.widthAnchor.constraint(equalToConstant: width).isActive = true
button.heightAnchor.constraint(equalToConstant: 32.0).isActive = true
button.centerYAnchor.constraint(equalTo: contentView.stackView.centerYAnchor).isActive = true

Finally, most important point: stackView.alignment = fill is the default value. Alignment is how much area the arrangedViews take up on the perpendicular axis (in the case of horizontal, fill will take up the full height).

To have it be centered on the perpendicular axis instead, use:

stackView.alignment = center

Upvotes: 1

Related Questions