I introduced some UIStackView's in my latest project, because it made the spacing of the views and adding other autolayout constraints a lot easier.
Only to discover that hidden views inside a UIStackView no longer 'participate' when autolayout does its thing.
I suppose this is often a great feature, but for this particular view I don't want that, is there a way to have the subviews of a UIStackView behave as if they were embedded in a plain UIView?
Or do I have no option but to resort to removing the UIStackViews? (and adding a whole lot of annoying 'spacer' views and constraints)
You need to set the compression resistance priority to 0 (not the content hugging) in code when you want to hide the view, and when you want to show again restore that value. Apart of that you need to add a constraint in interface builder to set the size of the view to 0.
The stack view manages the layout of all the views in its arrangedSubviews property. These views are arranged along the stack view's axis, based on their order in the arrangedSubviews array. The exact layout varies depending on the stack view's axis , distribution , alignment , spacing , and other properties.
It is by design that hidden arranged subviews are not only hidden but no longer contribute to the layout either. It's a major feature that cannot be achieved easily with auto layout.
If you want to prevent this, then you can wrap your view within another view. Instead of hiding the direct subview of the UIStackView (the wrapper view in the new setup), hide the inner view (the same way as in the old setup except it is now nested). As the direct subview is visible, UIStackView won't reclaim the space. But the user can't see any content as the view content is hidden.
Instead of hiding the subview, you can just turn its alpha to 0. This way the subview won't be visible but it will participate in the layout.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With