IOS stackview addArrangedSubview add at specific index
Asked Answered
T

2

55

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

something like:

stackView.addArrangedSubview(nibView, atIndex: index)
Tequila answered 23/12, 2015 at 11:2 Comment(0)
B
107

You mean you want to insert, not add:

func insertArrangedSubview(_ view: UIView, atIndex stackIndex: Int)
Benedict answered 23/12, 2015 at 11:5 Comment(2)
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 onBlaubok
@Blaubok for your requirement, maybe you should try collectionview instead.Verniavernice
H
3

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)
            }
        }
    }
}
Historian answered 4/12, 2020 at 10:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.