How to put a stack view below another stack view

Viewed 43

I want to place the dateInfo stack view below the userInfoStack view. This is what it currently looks like enter image description here

How can I place the stack view vertically one below the other? I tried adjusting the distribution, but it doesn't solve the problem.

I am trying to create reusable banner in the UI.

 class UserCell: UIView {
  
    var rootStack = UIStackView()
    var userInfoStackView = UIStackView()
    var dateInfoStackView = UIStackView()
    

    override init(frame: CGRect) {
        super.init(frame: frame)
        setUPViews()
        addComponents()
        layoutComponents()
    }


    private func setUPViews(){
        rootStack = UIStackView()
        rootStack.translatesAutoresizingMaskIntoConstraints = false
        rootStack.alignment = .center
        rootStack.distribution = .fillEqually
        rootStack.spacing = 5
       
        userInfoStackView = UIStackView()
        userInfoStackView.axis = .horizontal
        userInfoStackView.spacing = 10

        dateInfoStackView = UIStackView()
        dateInfoStackView.axis = .vertical
        dateInfoStackView.spacing = 2

    }
    private func addComponents() {
         userInfoStackView.addArrangedSubview(nameLabel)
         userInfoStackView.addArrangedSubview(compCode)
        
         dateInfoStackView.addArrangedSubview(captionLabel)
         dateInfoStackView.addArrangedSubview(dateLabel2)   
      }
      private func layoutComponents() {
          addSubview(rootStack)
          rootStack.addArrangedSubview(userInfoStackView)
          rootStack.addArrangedSubview(dateInfoStackView)
          rootStack.snp.makeConstraints { (make) in
              make.edges.equalToSuperview()
          }
      }
        
}
1 Answers

The axis on the rootStack is not set

Try rootStack.axis = .vertical

since the default value for axis of a UIStackView is horizontal your views are laid out horizontally next to each other

Also set to rootStack.alignment = .leading to align everything to the left margin

So your implementation should look like below

rootStack = UIStackView()
rootStack.translatesAutoresizingMaskIntoConstraints = false
rootStack.axis = .vertical
rootStack.alignment = .leading
rootStack.distribution = .fillEqually
rootStack.spacing = 5
Related