I've yet to find an answer for this anywhere and I'm not sure if it's possible, but I'm trying to right align a horizontal UIStackView
, so that if subviews are hidden they move towards the right side not the left. Either programmatically (in Swift) or using the Interface Builder
UIStackView
s 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
Or you can do it in code, using the view's semanticContentAttribute
stackView.semanticContentAttribute = .forceRightToLeft
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
I had a horizontally oriented UIStackView
containing two UIView
s; hiding one of the views led to the other spreading full-width. Adding a width constraint to the remaining view resulted in keeping the desired width, but it shifted to the right.
TL;DR
Add a hidden UIView
to the stack view which shows when the other is hidden for spacing.
stackView.distribution = UIStackViewDistributionFill;
& stackView.alignment = UIStackViewAlignmentCenter;
–
Mccready © 2022 - 2024 — McMap. All rights reserved.