Layout margins within a UIStackView

The UIStackView property isLayoutMarginsRelativeArrangement allows insets similar to margin constraints on subviews in a UIView.

Let’s consider a simple single-subview example:

let containedView = UIView()
containedView.backgroundColor = .purple

let stackView = UIStackView()
stackView.addArrangedSubview(containedView)

You can then configure layoutMargins and enable them like so:

stackView.layoutMargins = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
stackView.isLayoutMarginsRelativeArrangement = true

This is what it looks like, before and after:

The subview stretches from edge to edge without margins

The subview is inset on all edges by 8 points