Home > Enterprise >  How to center elements of a stack view in a scroll view vertically?
How to center elements of a stack view in a scroll view vertically?

Time:07-31

I have enter image description here

I am not sure how to put them in the center of the screen since the stack view just surrounds the existing views. Do I put layout constraints on the buttons themselves? Or is there an attribute of the stack view like alignment or distribution that I can use?

CodePudding user response:

Try give width constraint to the buttons:

for _ in 1 ..< 100 {
        let vw = UIButton(type: UIButton.ButtonType.system)
        vw.setTitle("Button", for: [])
        vw.snp.makeConstraints { make in
            make.width.equalTo(view.frame.width)
        }
        stackView.addArrangedSubview(vw)
    }

Output:

enter image description here

CodePudding user response:

Adjust the UIStackView to fill UIScrollView width:

stackView.snp.makeConstraints { (make) in
     make.edges.equalToSuperview()
     make.width.equalToSuperview()
 }
  • Related