如何在后台添加子视图

时间:2018-08-02 11:07:09

标签: ios swift uiview uistackview

我有一个stackview,其中3个项目垂直对齐。现在,我创建了一个Uiview来为其添加边框,并在stackview中也添加了边框,以将其显示为带有圆角的彩色背景。

我成功创建了一个视图并将其附加到UIStackview。但似乎它涵盖了UIStackView的所有其他排列的子视图。而我想将其他子视图放在前面。请帮我。这是下面的代码:

extension UIStackView {
    override open var backgroundColor: UIColor? {

        get {
            return super.backgroundColor
        }

        set {

            super.backgroundColor = newValue

            let tag = -9999
            for view in subviews where view.tag == tag {
                view.removeFromSuperview()
            }

            let subView = UIView()
            subView.tag = tag
            subView.backgroundColor = newValue
            subView.translatesAutoresizingMaskIntoConstraints = false
            subView.layer.cornerRadius = 5
            subView.layer.masksToBounds = true
            subView.layer.borderColor = CommonUtils.hexStringToUIColor(hex: "#C2C2C2").cgColor
            subView.layer.borderWidth = 0.35
            self.addSubview(subView)
            subView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
            subView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
            subView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
            subView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
        }

    }
}

2 个答案:

答案 0 :(得分:1)

您可以尝试

self.insertSubview(subView, at:0)

代替

self.addSubview(subView)

答案 1 :(得分:0)

您可以使用self.view.bringSubview(toFront: yourView)