I have a stackview with three subviews:
stackView.spacing = 8.0
stackView.addArrangeSubview(view1)
stackView.addArrangeSubview(view2)
stackView.addArrangeSubview(view3)
At some point, I add custom spacing after view2:
stackView.setCustomSpacing(24.0, after: view2)
Now, I want to remove the custom spacing. Is this possible using UIStackView? The only way I can think of is
stackView.setCustomSpacing(8.0, after: view2)
but this will break if I ever change the spacing of my stackView to something other than 8.0, because spacing will remain 8.0 after view2.
Try this extension:
extension UIStackView {
// remove all custom spacing
func removeCustomSpacing() -> Void {
let a = arrangedSubviews
arrangedSubviews.forEach {
$0.removeFromSuperview()
}
a.forEach {
addArrangedSubview($0)
}
}
// remove custom spacing after only a single view
func removeCustomSpacing(after arrangedSubview: UIView) -> Void {
guard let idx = arrangedSubviews.firstIndex(of: arrangedSubview) else { return }
removeArrangedSubview(arrangedSubview)
insertArrangedSubview(arrangedSubview, at: idx)
}
}
Use it simply as:
myStackView.removeCustomSpacing()
or, if you are setting custom spacing on multiple views, and you want to remove it from only one view, use:
theStackView.removeCustomSpacing(after: view2)
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