Stack Views in Xcode allow you to lay out a series of views horizontally or vertically and are a trivial solution to create layouts of increasing complexity.
We talked about constraints in the previous article using Auto Layout, however the more elements you add to your view, the more constraints you have to add and managing these can become quite difficult. Using the
UIStackView, you’re able to configure alignment and spacing properties, and how the elements adjust themselves within the given device widths.
Let’s assume that your application has three simple buttons. The image below shows these buttons on an iPhone 6s portrait orientation.
When running the project using this view the buttons appear in their expected position, however if we rotate the device to its horizontal orientation, only two of the buttons show. You’ll also notice that the buttons are not vertically centred.
To resolve this, we can add the buttons in a Stack View. Start by selecting all three buttons, and then choosing the
Stack option, which is the first option in the bottom right hand corner of the view.
Now the buttons have now been grouped together by the Stack View, and the buttons are represented under the stack view when viewing the View Controller Scene structure.
By clicking on the
Attributes Inspector menu, you can choose to space out the buttons using the
The final step is to add constraints to the Stack View to centralise the group of buttons. Highlight the Stack View, and check both the ‘Horizontally in Container’ and ‘Vertically in Container’ checkboxes.
If orange lines appear on your view, resolve the Auto Layout issues and the group of buttons will now be aligned when switching device orientation from portrait to landscape.
This is just a simple example of using the UiStackView. In the example, we only needed to add two constraints, whereas not using a Stack View we may have needed to add at least 2 constraints per button. There will be more complex scenarios where multiple Stack Views are needed, but this should give you a basic idea as to why they are useful to use in app development.