Get View's index from UIStackView
Asked Answered
S

1

8

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

Stimulative answered 19/9, 2018 at 15:50 Comment(0)
E
20

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)
}
Electrophorus answered 19/9, 2018 at 15:59 Comment(1)
firstIndex(of:) is for xcode 10 , try your index(ofRaw

© 2022 - 2024 — McMap. All rights reserved.