Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save m25lazi/27d701e8be9183f7d9767d84a82343fd to your computer and use it in GitHub Desktop.
Save m25lazi/27d701e8be9183f7d9767d84a82343fd to your computer and use it in GitHub Desktop.
Sample implementation of vertically scrollable stack view
import UIKit
class VerticalScrollableStackViewController: UIViewController {
let scrollView: UIScrollView = UIScrollView(frame: .zero)
let stackView: UIStackView = UIStackView(frame: .zero)
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .gray
self.view.addSubview(self.scrollView)
self.setupScrollViewConstraints()
self.setupStackViewElements()
self.addStackView(to: self.scrollView)
}
func setupScrollViewConstraints() {
self.scrollView.translatesAutoresizingMaskIntoConstraints = false
self.scrollView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
self.scrollView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
self.scrollView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
self.scrollView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
}
func setupStackViewElements() {
self.stackView.axis = .vertical
let redView = getFullWidthView(height: 100.0, color: .red)
self.stackView.addArrangedSubview(redView)
let blueView = getFullWidthView(height: 200.0, color: .blue)
self.stackView.addArrangedSubview(blueView)
let yellowView = getFullWidthView(height: 300.0, color: .yellow)
self.stackView.addArrangedSubview(yellowView)
let whiteView = getFullWidthView(height: 400.0, color: .white)
self.stackView.addArrangedSubview(whiteView)
let orangeView = getFullWidthView(height: 500.0, color: .orange)
self.stackView.addArrangedSubview(orangeView)
}
func addStackView(to view: UIView) {
view.addSubview(self.stackView)
self.stackView.translatesAutoresizingMaskIntoConstraints = false
self.stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
self.stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
self.stackView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
self.stackView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
self.stackView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
}
func getFullWidthView(height: CGFloat, color: UIColor) -> UIView {
let view = UIView(frame: CGRect(origin: .zero, size: CGSize(width: self.view.frame.width - 5.0, height: height)))
view.backgroundColor = color
view.heightAnchor.constraint(equalToConstant: height).isActive = true
return view
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment