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

168 Views Asked by At

I have this code I found to put a stack view with many buttons inside of a scroll view.

import UIKit
import SnapKit

class ViewController: UIViewController {
    var scrollView: UIScrollView!
    var stackView: UIStackView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let scrollView = UIScrollView()
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(scrollView)
        
        scrollView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        let stackView = UIStackView()
        stackView.translatesAutoresizingMaskIntoConstraints = false
        stackView.axis = .vertical
        scrollView.addSubview(stackView)
        
        stackView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        for _ in 1 ..< 100 {
            let vw = UIButton(type: UIButtonType.system)
            vw.setTitle("Button", for: [])
            stackView.addArrangedSubview(vw)
        }
    }
}

However this creates buttons on the left.

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?

2

There are 2 best solutions below

0
Mahmoud Eissa On BEST ANSWER

Adjust the UIStackView to fill UIScrollView width:

stackView.snp.makeConstraints { (make) in
     make.edges.equalToSuperview()
     make.width.equalToSuperview()
 }
0
Asteroid On

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