Elton Santana
Elton Santana

Reputation: 989

IOS stackview addArrangedSubview add at specific index

How is it possible to add a arranged subview in a particular index in a UIStackView?

something like:

stackView.addArrangedSubview(nibView, atIndex: index)

Upvotes: 55

Views: 23095

Answers (2)

chrigu
chrigu

Reputation: 145

if you don't want to struggle with the index you can use this extension

extension UIStackView {
    func insertArrangedSubview(_ view: UIView, belowArrangedSubview subview: UIView) {
        arrangedSubviews.enumerated().forEach {
            if $0.1 == subview {
                insertArrangedSubview(view, at: $0.0 + 1)
            }
        }
    }
    
    func insertArrangedSubview(_ view: UIView, aboveArrangedSubview subview: UIView) {
        arrangedSubviews.enumerated().forEach {
            if $0.1 == subview {
                insertArrangedSubview(view, at: $0.0)
            }
        }
    }
}

Upvotes: 5

Wain
Wain

Reputation: 119041

You mean you want to insert, not add:

func insertArrangedSubview(_ view: UIView, atIndex stackIndex: Int)

Upvotes: 107

Related Questions