skip to Main Content

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

Answers


  1. 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

    Login or Signup to reply.
  2. Adjust the UIStackView to fill UIScrollView width:

    stackView.snp.makeConstraints { (make) in
         make.edges.equalToSuperview()
         make.width.equalToSuperview()
     }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search