jsloop
5/25/2019 - 9:37 AM

Simple Scrolling UIStackView

//
//  SimpleScrollingStack.swift
//  A super-simple demo of a scrolling UIStackView in iOS 9
//
//  Created by Paul Hudson on 10/06/2015.
//  Learn Swift at www.hackingwithswift.com
//  @twostraws
//

import UIKit

class ViewController: UIViewController {
	var scrollView: UIScrollView!
	var stackView: UIStackView!

	override func viewDidLoad() {
		super.viewDidLoad()

		scrollView = UIScrollView()
		scrollView.translatesAutoresizingMaskIntoConstraints = false
		view.addSubview(scrollView)

		view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[scrollView]|", options: .AlignAllCenterX, metrics: nil, views: ["scrollView": scrollView]))
		view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[scrollView]|", options: .AlignAllCenterX, metrics: nil, views: ["scrollView": scrollView]))


		stackView = UIStackView()
		stackView.translatesAutoresizingMaskIntoConstraints = false
		stackView.axis = .Vertical
		scrollView.addSubview(stackView)

		scrollView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[stackView]|", options: NSLayoutFormatOptions.AlignAllCenterX, metrics: nil, views: ["stackView": stackView]))
		scrollView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[stackView]", options: NSLayoutFormatOptions.AlignAllCenterX, metrics: nil, views: ["stackView": stackView]))

		for _ in 1 ..< 100 {
			let vw = UIButton(type: UIButtonType.System)
			vw.setTitle("Button", forState: .Normal)
			stackView.addArrangedSubview(vw)
		}
	}

	override func viewDidLayoutSubviews() {
		super.viewDidLayoutSubviews()
		scrollView.contentSize = CGSize(width: stackView.frame.width, height: stackView.frame.height)		
	}
}