2017-04-11 UIStackView playground

Here's a nice way to play with a UIStackView. Copy and paste the following code into a playground, and next to the final line, click the screen icon to permanently show it. Then adjust the parameters of the playground where necessary.

    import UIKit
    var view = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
    view.backgroundColor = UIColor.yellow
    let label1 = UILabel()
    label1.text = "label 1"
    let label2 = UILabel()
    label2.text = "label 2"
    let spacer1 = UIView()
    spacer1.backgroundColor = UIColor.green
    spacer1.translatesAutoresizingMaskIntoConstraints = false
    spacer1.widthAnchor.constraint(equalToConstant: 3).isActive = true
    let spacer2 = UIView()
    spacer2.backgroundColor = UIColor.gray
    let stackView = UIStackView(arrangedSubviews: [label1, spacer1, label2, spacer2])
    stackView.distribution = .fill
    stackView.axis = .horizontal
    stackView.translatesAutoresizingMaskIntoConstraints = false
    stackView.spacing = 20
    view.addSubview(stackView)
    stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
    stackView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    stackView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
    view.layoutIfNeeded()
    view

The result should look something like this:

uistackview playground 2017-04-11.png