Easier layouts with UIStackView

With iOS 9, Apple added an iOS version of macOS's NSStackView to UIKit. It's called UIStackView. This was a huge improvement because this view makes stacked layouts, such as the stack of labels and values the contact details page contains, a whole lot easier to create and maintain. The most common use case for a UIStackView is when you have a couple of views that are laid out relative to each other with equal spacing in between the items.

The layout we created earlier for the contact details page can definitely benefit from using UIStackView. The list of labels that displays a user's details in a list can be converted to a UIStackView. Currently, every label has a constraint to the labelĀ beneath it. This means that adding or removing a label right in the middle would involve removing constraints, reordering labels, and then adding new constraints.

With UIStackView, you can simply drag in all the labels you want displayed, configure the UIStackView class's layout, and reorder the labels by dragging them around. Constraints will be added and maintained by UIStackView automatically. You just have to configure its properties. Let's see how.