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 directionalLayoutMargins and enable them like so:

stackView.directionalLayoutMargins = NSDirectionalEdgeInsets(
    top: 8,
    leading: 8,
    bottom: 8,
    trailing: 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