Search code examples
iosswiftuiscrollviewuistackviewsnapkit

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


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?


Solution

  • Adjust the UIStackView to fill UIScrollView width:

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