IOS stackview addArrangedSubview 添加到特定索引

IOS stackview addArrangedSubview add at specific index

如何在 UIStackView 的特定索引中添加排列好的子视图?

类似于:

stackView.addArrangedSubview(nibView, atIndex: index)

你的意思是你想插入,而不是添加:

func insertArrangedSubview(_ view: UIView, atIndex stackIndex: Int)

如果你不想为索引而烦恼,你可以使用这个扩展

extension UIStackView {
    func insertArrangedSubview(_ view: UIView, belowArrangedSubview subview: UIView) {
        arrangedSubviews.enumerated().forEach {
            if [=10=].1 == subview {
                insertArrangedSubview(view, at: [=10=].0 + 1)
            }
        }
    }
    
    func insertArrangedSubview(_ view: UIView, aboveArrangedSubview subview: UIView) {
        arrangedSubviews.enumerated().forEach {
            if [=10=].1 == subview {
                insertArrangedSubview(view, at: [=10=].0)
            }
        }
    }
}