ffritz
ffritz

Reputation: 2261

UIStackView with setCustomSpacing for dynamic number of Subviews

I have a stackview with a dynamic number and type of subviews, but I always add a static element as the last element to the stackview, which needs 30 spacing before it.

I have the issue that the following code seems to assign the 30 spacing for every view, eventhough it should only do it to the last iteration:

stackView = {
    let stackView = UIStackView()
    stackView.axis = .vertical
    stackView.distribution = .equalSpacing
    stackView.translatesAutoresizingMaskIntoConstraints = false
    
    return stackView
}()

for (index, element) in elements.enumerated() {
    let initializedClass = element
    let initializedView = initializedClass.view

    self.addChild(initializedClass)
    initializedClass.didMove(toParent: self)

    self.stackView.addArrangedSubview(initializedView!)
    // default spacing of 5
    var spacing = 5

    if index == elements.endIndex - 1 {
        // the last element should have 30 spacing after it
        // what happens is that all elements have 30 spacing
        spacing = 30
    }

    self.stackView.setCustomSpacing(CGFloat(spacing), after: initializedView!)
}

// I'm adding another element here

Question: Why is there 30 spacing for every added subview, instead of just the last?

Upvotes: 0

Views: 839

Answers (1)

πter
πter

Reputation: 2217

Your stackView.distribution = .equalSpacing contradicts with the custom spacing you are trying to define. With equalSpacing you tell the UIStackView to arrange its views so that they fill the available space along the stack view’s axis, but at the same time you tell it to set your custom spacing which causes an issue. Instead of .equalSpacing try to use stackView.distribution = .fill. Also see: equalSpacing

Upvotes: 1

Related Questions