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.
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
Try give width constraint to the buttons:
Output:
Adjust the
UIStackView
to fillUIScrollView
width: