STACK VIEW IN iOS 9

03 / Nov / 2015 by Ashish Jain 1 comments

Gone are the days when every scrollable grid is either TableView or CollectionView. Enter StackView.!

Stack view is a simple class that allows to stack layout views in either a column or a row. What makes it more helpful is the elimination of the need to add the constraints. It applies Auto Layout to the views within the stack view. Stack view can also be placed within another stack view to give a better sense of UI.

A Simple guide to implement stack view.

  1. Drag stack views from the object library and drop views onto them.
  2. Using the Inspector check the axis is “Horizontal/Vertical”, set the alignment to “Centre/Fill/Leading/Trailing”.
  3. Keep the default “fill” or one of (Fill equally/Fill propitiously/Equal Spacing/Equal Centering) distribution.
  4. Increase the spacing between the views to “16”(or any suitable values).

xcode_screenshot

To give more idea this is how attributes work.

stackViewiOS

Dynamically updating a Stack View

In stack view in can updates its layout when views are added or removed automatically from the arrangedSubviews array. Removing a view is also sufficient for it to be removed from the layout constraints. Changes to the stack view properties can also be animated using the same technique as in Animating Auto layout Constraints.

For example :
If we connect the UISwitch to an action we can animate switching between a horizontal or vertical layout of the views:

1. Create an action of UISwitch :

@IBAction func axisChange(sender: UISwitch) {
UIView.animateWithDuration(1.0) {
self.updateConstraintsForAxis()

        //Below the definition of function updateConstraintsForAxis()

    }
}

//Function Definition

private func updateConstraintsForAxis() {
if (axisSwitch.on) {
stackView.axis = .Horizontal
} else {
stackView.axis = .Vertical
}
}

FOUND THIS USEFUL? SHARE IT

comments (1 “STACK VIEW IN iOS 9”)

Leave a Reply

Your email address will not be published. Required fields are marked *