If you hate auto layout, you may be surprised to learn Apple does too. In Xcode 7 Apple introduced a new way to work with constraints called stack views. Stacks are containers that keep views aligned automatically. Originally announced as a lazy man’s auto layout, you do need to understand auto layout to use it correctly. For this demo and introduction to stack views, we’ll make an options page for dessert pies. We’ll suppose we will use this as a modal view, so we need to add our own navigation.
Horizontal Stack Views
Create a new project and go to the storyboard. Add a label titled Pie Options. Add two buttons titled Cancel and Done. Place them toward the top of the scene like this:
Select all three items. Click the stack button in the Auto layout menu buttons.
It has no menu, but there will be a change in the storyboard. Your three views now are embedded in a horizontal stack view.
Stack views can be pinned like any other view. Pin the stack view 0 points up, 0 Points Left and 0 points right, with update set to Items of new constraints
Besides the odd placement of the items in the stack view, the labels and buttons are not aligned. In the attributes menu for the stack view, Select First Baseline for Alignment and Fill Equally for Distribution.
Our stack view rearranges to have equal width for all the subviews, and the text in the labels and buttons align to the baseline.
However the Label is still left justified. Select the label and center justify it.
Our pseudo toolbar is now complete, a lot faster than pinning the three views
Vertical Stack Views
Add a label Topping and four buttons Whipped cream,Chocolate Sauce,Caramel Sauce and None. Give the buttons a blue background with white text. Arrange them vertically like this:
Select the label and buttons, then click the stack view button. Stack views know you want a horizontal or vertical view by context. This gets a vertical stack view.
Stack view also take by context what type of Alignment and distribution they’ll use. Due to the centered labels, the stack view centered the buttons. Change the Alignment to Fill. Also change the spacing to 3.
This makes equal width buttons and a 3 point space between them.
Pin the new stack view 10 points up, 0 points left and 0 points right. Update the frame. Checking in the assistant editor’s preview mode, we see that both landscape and portrait adapts to the new layout.
In the preview and storyboard, you’ll see a background to the stack view. In an app, a stack view always has a background of clearColor
.
Don’t waste your time, trying to change the background.
That’s the basics of Stack views. In my upcoming book Practical Autolayout for Xcode 7, we’ll cover more about stack views including embedding them, and some of the perils of stack views.
Leave a Reply