How do you right align a horizontal UIStackView?

What worked best for me was putting my horizontal stackview inside a vertical stackview and set the vertical one's alignment to leading


Unlike the other answers, the solution is actually fairly simple. What you need is to add a trailing constraint that pins the stack view to the trailing edge of its superview and then also add a leading constraint that pins it to the leading edge of the superview.

The trick, however, is changing the leading stackview constraint relation from equal to greater than or equal.

That will allow the leading edge of the stack view to snap over to the intrinsic width of the contents of the stackview, effectively pinning everything to the trailing edge.

Vertical stack views are similar. Pin the top with equals, and pin the bottom with less than or equal.

So:

stackView.leadingAnchor.constraint(greaterThanOrEqualTo: parent.leadingAnchor).isActive = true

stackView.trailingAnchor.constraint(equalTo: parent.trailingAnchor).isActive = true

stackView.distribution = .equalSpacing

UIStackViews align according to the user's text direction, i.e. left aligned for English and other Roman script languages, or right aligned for languages such as Hebrew.

In my opinion, changing this for layout reasons may be a misuse of the text direction APIs, and a bit of a hack, but with that in mind:

You can change the direction for a particular view in interface builder, using the Semantic drop down, which has options for 'Force Left-to-Right' and 'Force Right-to-Left', which will change the direction they pop to but also the order they are shown in. So you will have to reverse the order of the elements in your stack view

Semantic selector in IB

Or you can do it in code, using the view's semanticContentAttribute

stackView.semanticContentAttribute = .forceRightToLeft