Search code examples
iosswiftuistackview

Get View's index from UIStackView


I have added 2 views in stackview with different size. Now When I click on plus button of any view, I just wanted to add a view right below that.

I am getting view by:

let index = superView.subviews.index(of: view)

and then I am doing:

superView.insertArrangedSubview(newView, index + 1)

but actually it is adding new view at different position.

So If I try to get index by .subview.index then it always returns last index


Solution

  • The arrangedSubviews and subviews arrays don't have to be the same (because a stack view can have a subview that is not “arranged”). Even if they have the same elements, they don't have to be in the same order.

    So:

    if let index = stackView.arrangedSubviews.firstIndex(of: view) {
        stackView.insertArrangedSubview(newView, at: index + 1)
    }