Override spacing for a UIStackView
Asked Answered
L

1

8

I frequently find that a UIStackView is perfect for a particular layout, except that I need some variable spacing between the arranged subviews. UIStackView uses its spacing property to arrange the views along its axis, but is there a way to override these? For example, I would love to be able to add a single manual constraint using the visual format to define the required gaps, and somehow de-prioritize those of the stack view.

I could forgo the UIStackView entirely of course, but the stack's ability to give back space between hidden subviews is pretty painful to replicate manually (adding and removing constraints based on which views are hidden, for example). I also tried wrapping individual subviews in their own stack views so that I can use the stack's layoutMargins to add a top-margin. But this then requires managing the wrapper-stack's own hidden state in addition to that of the subview it contains (surprisingly - to me - a UIStackView whose arrangedSubviews are all hidden is not automatically hidden itself, so does not yield its spacing and margins back to its own superview).

Lethargy answered 26/3, 2016 at 18:11 Comment(1)
Not the prettiest but you can use an extension to add an array of "spaces" that create empty views: #32999659Secor
P
4

From iOS 11 it is possible to use:

stackView.setCustomSpacing(spacing: CGFloat, after: UIView)
Pottage answered 25/11, 2017 at 19:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.