aligning view top to the bottom of another view inside vertical stackview

Viewed 1144

I have a label and image attached in a vertical stack view. I want them to be centered to the stack view, but not larger. I also want the top of the label to be aligned to the bottom of the image.

I tried those constraints:

screenshot

But the label is stuck to the bottom of the stack view.

I also tried:

NSLayoutConstraint(item: stackView,
    attribute: .top,
    relatedBy: .greaterThanOrEqual,
    toItem: contentView,
    attribute: .top,
    multiplier: 1,
    constant: 0).isActive = true

NSLayoutConstraint(item: stackView,
    attribute: .bottom,
    relatedBy: .greaterThanOrEqual,
    toItem: contentView,
    attribute: .bottom,
    multiplier: 1,
    constant: 0).isActive = true

NSLayoutConstraint(item: stackView,
    attribute: .left,
    relatedBy: .greaterThanOrEqual,
    toItem: contentView,
    attribute: .left,
    multiplier: 1,
    constant: 0).isActive = true

NSLayoutConstraint(item: stackView,
    attribute: .right,
    relatedBy: .greaterThanOrEqual,
    toItem: contentView,
    attribute: .right,
    multiplier: 1,
    constant: 0).isActive = true

NSLayoutConstraint(item: stackView,
    attribute: .centerX,
    relatedBy: .equal,
    toItem: contentView,
    attribute: .centerX,
    multiplier: 1,
    constant: 0).isActive = true

NSLayoutConstraint(item: stackView,
    attribute: .centerY,
    relatedBy: .equal,
    toItem: contentView,
    attribute: .centerY,
    multiplier: 1,
    constant: 0).isActive = true

NSLayoutConstraint(item: imageView,
    attribute: .height,
    relatedBy: .equal,
    toItem: stackView,
    attribute: .height,
    multiplier: 0.5,
    constant: 0).isActive = true

But now the image top is stuck to the top of the content view top, and the label bottom is stuck to the bottom of the content view bottom.

1 Answers

A UIStackView arranges its subviews.

In your case, you have a UIImageView and a UILabel as arranged subviews of a vertical stack view. So, the label will always be below the image view.

I'm assuming you have additional views to add to the stack view -- if so,

  • To get the label "top-aligned" with the image view, embed both the label and the image view in a new UIView, set the constraints to pin the label to the top, then add that UIView to your stack view.

If not,

  • You probably don't want to use the stack view at all.
Related