51

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

something like:

stackView.addArrangedSubview(nibView, atIndex: index)
Elton Santana
  • 950
  • 3
  • 11
  • 22

2 Answers2

103

You mean you want to insert, not add:

func insertArrangedSubview(_ view: UIView, atIndex stackIndex: Int)
Wain
  • 118,658
  • 15
  • 128
  • 151
  • I am adding labels as subview what happens is that if I keep Stackview axis horizontal, I get one horizontal strip of UILabels if I keep it vertical, I get a vertical strip of UILabels where labels are arranged one below the other its arranged like this label1 label2 label3 and so on But what I am trying to achieve is this label1, label2(if it fits) otherwise take it below label3, label4 label5 and so on – Ranjit Jun 27 '16 at 16:07
  • @Ranjit for your requirement, maybe you should try collectionview instead. – anoo_radha Jan 10 '19 at 13:49
2

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)
            }
        }
    }
}
chrigu
  • 115
  • 1
  • 4