Snapkit: Make right and left constraints in UIStackView

Created on 7 Jun 2019  路  2Comments  路  Source: SnapKit/SnapKit

  • [x] I have looked at the Documentation
  • [x] I have read the F.A.Q.
  • [x] I have filled out this issue template.

Issue Info

Info | Value |
-------------------------|-------------------------------------|
Platform | ios
Platform Version | 12.0.1
SnapKit Version | 5.0.0
Integration Method | cocoapods

Issue Description

I would like to set right and left constraints of a subview in a vertical UIStackView, but when I apply the followed code, just the left constraint worked.

verticalStackView.addArrangedSubview(subview)

subview.snp.makeConstraints { make in
 make.left.right.equalToSuperview().inset(15)
 make.height.equalTo(44)
}

How to fix that ?

Most helpful comment

Same issue here and I solved it.
If you set alignment to fill the subview will fills to fit the size of the stackview.
So you just set the alignment to center that's it.

All 2 comments

Autolayout wouldn't work in a UIStackview - that isn't how they are intended to be used.

You _could_ add a container UIView to the stack and make your subview a child of _that_.

This would allow you to enable constraints on your view.

        let myVerticalStackview = UIStackView(frame: .zero)
        myVerticalStackview.axis = .vertical

        let myContainerView = UIView(frame: .zero)
        let mySubview = UIView(frame: .zero)

        myContainerView.addSubview(mySubview)

        mySubview.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(15)
            make.height.equalTo(44)
        }

        [myContainerView].forEach { myVerticalStackview.addSubview($0) }

You could also consider using a spacer view.

        let myVerticalStackview = UIStackView(frame: .zero)
        myVerticalStackview.axis = .vertical
        myVerticalStackview.alignment = .center

        let mySubview = UIView(frame: .zero)
        mySubview.heightAnchor.constraint(equalToConstant: 44)

        let spacerView = UIView(frame: .zero)
        spacerView.widthAnchor.constraint(equalToConstant: 15)

        [spacerView, mySubview, spacerView].forEach { view in
            view.translatesAutoresizingMaskIntoConstraints = false
            myVerticalStackview.addArrangedSubview(view)
        }

Same issue here and I solved it.
If you set alignment to fill the subview will fills to fit the size of the stackview.
So you just set the alignment to center that's it.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

seljabali picture seljabali  路  3Comments

aeves313 picture aeves313  路  4Comments

romk1n picture romk1n  路  3Comments

lolgear picture lolgear  路  5Comments

NicholasTD07 picture NicholasTD07  路  8Comments