Search code examples
iosuiscrollviewautolayoutuistackview

How to right align a UIStackView inside a UIScrollView when the stack view's size is smaller than scroll view?


Please look at the below picture of my storyboard to understand the layout of my views.

enter image description here

On the left side is a horizontal UIStackView with 2 buttons. This is okay.

On the right side of the above stack view is a UIScrollView which has a horizontal UIStackView inside it.

I basically want the right stack view to be able to have many buttons in it.

If the right stack view's size exceeds the scroll view's width, then it should be scrollable to show remaining buttons.

This works fine so far and I was able to achieve this by setting the right stack view's edges to the contentLayoutGuide of the parent scroll view and setting the right stack view's height equal to the frameLayoutGuide of the parent scroll view.

This allows me to scroll successfully if there are too many buttons.

The problem I am facing is that if there's only a few buttons to not be enough to be scrollable, then I want those buttons to be right aligned. Basically, the UIScrollView should align the content stack view on the right side. Currently, all buttons are aligned to the left side.

I want it to look like this:

enter image description here


Solution

  • I figured out the solution after posting my question.

    1. I added an extra view at the beginning of the right UIStackView. This is basically a spacer view with no constraints and background color set to transparent. It is important NOT to set it to hidden and instead use transparent background color because UIStackView don't render hidden views and then this solution won't work. With this said, for this Stack Overflow answer, I have this view's background color set to purple to make things easier to understand.

    2. I added a new width constraint on the right UIStackView and made it greater than or equal to frameLayoutGuide width.

    Here's how it looks:

    enter image description here