Wednesday, March 2, 2016

iOS UIStackView

With the introduction of UIStackView, the alignment and auto layout tasks become trivial. Stack views provide a way to lay out a series of views horizontally or vertically. By configuring a few simple properties such as alignment, distribution, and spacing, you can define how the contained views adjust themselves to the available space. A stack view can distribute its views along its axis in various ways, and one of the ways is with an equal amount of spacing between each view. Embedding existing views into a new stack view is easy. First, select all of the buttons at the bottom of the Spot Info View Controller scene by clicking on one, then Command-click on the other two:

Once selected, click on the new Stack button in the Auto Layout toolbar at the bottom right of the storyboard canvas. Another option is to use Editor > Embed In > Stack View

When we embed a view in a stack view, any constraints to other views are removed. Now, click the Pin button on the Auto Layout toolbar to add constraints to it: Adding constraints is same as any other view. Double-check the numbers for the top, leading, trailing, and bottom constraints and make sure that the I-beams are selected. Then click on Add 4 Constraints. However, when doing this the components inside get stretched.

The property that determines how a stack view lays out its views along its axis is its distribution property. Currently, it’s set to Fill, which means the contained views will completely fill the stack view along its axis. To accomplish this, the stack view will only expand one of its views to fill that extra space; specifically, it expands the view with the lowest horizontal content hugging priority, or if all of the priorities are equal, it expands the first view.

If we want to distribute the spacing equally, go to the Attributes inspector. Change the Distribution from Fill to Equal Spacing:

In order to solve this problem without a stack view, you would have had to use spacer views, one between each pair of buttons. You’d have to add equal width constraints to all of the spacer views as well as lots of additional constraints to position the spacer views correctly.

References:

http://www.raywenderlich.com/114552/uistackview-tutorial-introducing-stack-views

No comments:

Post a Comment