PJR
PJR

Reputation: 13180

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

Upvotes: 8

Views: 10937

Answers (1)

rob mayoff
rob mayoff

Reputation: 385998

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)
}

Upvotes: 21

Related Questions