Using UIStackView for centralized viewing

I am trying to set up a simple container view in IB using UIStackView. I want this container to center its only ordered submission and respect the internal size of the content of the view.

Unfortunately, for any possible alignment and distribution configuration, the subview is stretched to fill the width along the axis.

This looks like a strange edge case or error, because as soon as I add a second view, everything behaves as expected, and both subheadings maintain their size, determined by the method of defining their own content.

I would like to understand why UIStackView behaves like this.

+5
source share
1 answer

UIStackView creates constraints with a priority of 1000 (maximum allowed priority), which is equal to UILayoutPriorityRequired . To meet these limitations, automatic layout is required.

Your restriction on "high" priority ( UILayoutPriorityDefaultHigh == 750 , I suppose) conflicts with the required restrictions on viewing the stack, so the machine will ignore your restriction.

If you set the limit priority to 1000, then the automatic layout will not be able to satisfy all the required restrictions. It will log an error, and it will break one of the limitations. You cannot choose which restriction it breaks.

Please note that only one of the three restrictions is required to solve the system, which may violate any of the three conflicting restrictions. However, violation of any one of the three conflicting restrictions does not leave a system that centers your view. Your view must either stretch or hug one end of the stack view, depending on which break of the machine breaks. And a future version of iOS may change the automatic layout so that different restrictions are violated and the layout changes.

It's unclear why you are trying to use the stack view to center your view. If you have only one view and you want to center it, make it a parent of a simple UIView instead of a UIStackView and set limits to center your view in the parent view.

If you use the stack view because sometimes you need more than one organized subset on the stack, you must add two hidden profiles (one at each end of the axis) in addition to your views (pages). Create a limit to the width or equal height between the delimiters.

+8
source

All Articles