BlackWolf
BlackWolf

Reputation: 5599

Remove custom spacing in UIStackView

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.

Upvotes: 4

Views: 2328

Answers (3)

DonMag
DonMag

Reputation: 77423

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)

Upvotes: 2

user9204495
user9204495

Reputation:

let spacingView = UIView()

[View1, View2, spacingView, View3].forEach { view in 
  stackView.addArrangeSubview(view)
}

when you want to remove it just remove the spacingView from the array and you can play with width and height of the spacingView like you prefer

Upvotes: 0

pacification
pacification

Reputation: 6018

You should re-create stackView with specific spacing and replace the old one with the new stackView.

Upvotes: 1

Related Questions