Dealing with Stacked Views in Code - The User Interface - iOS 9 Swift Programming Cookbook (2015)

iOS 9 Swift Programming Cookbook (2015)

Chapter 3. The User Interface

3.5 Dealing with Stacked Views in Code

Problem

You want to programmatically manipulate the contents of stack views.

Solution

Use an instance of the UIStackView.

Discussion

For whatever reason, you might want to construct your stack views programmatically. I do not recommend this way of working with stack views because IB already can handle most of the situations where you would want to use stack views, and then some. But if you absolutely have to use stack views in your app, simply instantiate UIStackView and pass it your arranged views.

You can also then set the axis property to either Vertical or Horizontal. Remember to set the distribution property as well, of type UIStackViewDistribution. Some of the values of this type are Fill, FillEqually and EqualSpacing. I also like to set the spacing property of the stack view manually so that I know how much space there is between my items.

Let’s say that we want to create a stack view like Figure 3-18. The stack view is tucked to the right side of the screen and every time we press the button, a new label will be appended to the stack view.

Figure 3-18. This is the stack view that we want to create

First define a stack view in your view controller:

var rightStack: UIStackView!

Then a few handy methods for creating labels and a button:

func lblWithIndex(idx: Int) -> UILabel{

let label = UILabel()

label.text = "Item \(idx)"

label.sizeToFit()

return label

}

func newButton() -> UIButton{

let btn = UIButton(type: .System)

btn.setTitle("Add new items...", forState: .Normal)

btn.addTarget(self, action: "addNewItem",

forControlEvents: .TouchUpInside)

return btn

}

func addNewItem(){

let n = rightStack.arrangedSubviews.count

let v = lblWithIndex(n)

rightStack.insertArrangedSubview(v, atIndex: n - 1)

}

NOTE

The addNewItem function will be called when the button is pressed.

When our view is loaded on the screen, we will create the stack view and fill it with the three initial labels and the button. Then we will set up its axis, spacing, and distribution. Once done, we’ll create its constraints:

override func viewDidLoad() {

super.viewDidLoad()

rightStack = UIStackView(arrangedSubviews:

[lblWithIndex(1), lblWithIndex(2), lblWithIndex(3), newButton()])

view.addSubview(rightStack)

rightStack.translatesAutoresizingMaskIntoConstraints = false

rightStack.axis = .Vertical

rightStack.distribution = .EqualSpacing

rightStack.spacing = 5

rightStack.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor,

constant: -20).active = true

rightStack.topAnchor.constraintEqualToAnchor(

topLayoutGuide.bottomAnchor).active = true

}

See Also