Search code examples
swiftautolayout

place UIView behind UILabel programmatically


I want to ask. I want to make a UIView behind uilabel, I`m creating segmented Controll from collectionview right now. how can I make uiview behind uilabel? this is my code

nameLabel.translatesAutoresizingMaskIntoConstraints = false
        addSubview(nameLabel)
        NSLayoutConstraint.activate([
            nameLabel.topAnchor.constraint(equalTo: topAnchor),
            nameLabel.leadingAnchor.constraint(equalTo: leadingAnchor),
            nameLabel.bottomAnchor.constraint(equalTo: bottomAnchor),
            nameLabel.trailingAnchor.constraint(equalTo: trailingAnchor)
            ])

        let backgroundView = UIView()
        backgroundView.backgroundColor = .white
        backgroundView.translatesAutoresizingMaskIntoConstraints = false
        addSubview(backgroundView)
        insertSubview(backgroundView, aboveSubview: nameLabel)
        backgroundView.leadingAnchor.constraint(equalTo: nameLabel.leadingAnchor).isActive = true
        backgroundView.bottomAnchor.constraint(equalTo: nameLabel.bottomAnchor).isActive = true
        backgroundView.widthAnchor.constraint(equalTo: nameLabel.widthAnchor, multiplier: 1).isActive = true
        backgroundView.heightAnchor.constraint(equalToConstant: 48).isActive = true

Solution

  • You can do with the @Vacawama answer, or you should notice that Apple provides 2 API like:

    func sendSubviewToBack(_ view: UIView)
    

    and

    func bringSubviewToFront(_ view: UIView)
    

    So you can deal with your view hierarchy programmatically.

    Maybe you can try to move the backgroundView above the label in your storyboard, so you can have it behind (as it's first in, first out in the storyboard).

    Or use sendSubviewToBack(backgroundView).

    Or use bringSubviewToFront(nameLabel).

    Or view.addSubview(backgroundView) then view.addSubview(nameLabel).