Overview
- Stack views are a UIElement introduced in iOS 9, which as the name suggests make it easy to stack views.
- You can have any UIView subclass inside of a UIStackView.
- They can have either a horizontal or vertical orientation
- You can control the alignment, distribution and spacing of a stack view
- Stack views can be nested inside each other. Here is 3 horizontal stack views in a vertical one
- You only need to create auto layout constraints for the stack views themselves as opposed to all the individual UIElements. Stack views create their own auto layout constraints for the UIElements within them based on the alignment, distribution and spacing settings you provide
Inserting Stack Views
Creating a vertical stack view that is this full size of the device that contains 3 horizontal stack views
Drag from the object library in the bottom right of storyboard. From there ctrl-click drag from the stack view element in the document outline to the parent view and select the first four constraints.
This will add the constraints we need, but the stack view will not be the correct size because the constraints that were automatically created have constant values that try to fix the size of the stack view to what the size was when it was drag dropped onto the view.
To fix this we need to edit the constant for each constraint, and can do that by clicking on each of them in the document outline and editing the constant in the attributes inspector to, in our case, 0 so it will match the size of its containing view
From there we can drag and drop three horizontal stack views from the object library to the document outline ensuring they are nested under the vertical stack view. We also need to make sure the alignment is set to fill and the distribution is set to fill equally so they will all be spaced evenly and given the same amount of screen real estate