Search code examples
iosswiftuitableviewuiviewhierarchy

How do I move UIView to the back?


I have a prototype cell with some labels and image views, all added thru Storyboard. I am trying to add a color background view behind these elements (sort of like a bubble view behind the text that is commonly used in messengers). Trying to add this bubble view through Storyboard became a nightmare because of constraints' conflicts. So I decided to add it programmatically right in the prototypeCell class:

let backgroundBubble = UIView()

override func awakeFromNib() {
    super.awakeFromNib()
    backgroundBubble.backgroundColor = .yellow
    backgroundBubble.translatesAutoresizingMaskIntoConstraints = false
    addSubview(backgroundBubble)
    let constraints = [
        backgroundBubble.topAnchor.constraint(equalTo: Label.topAnchor, constant: 0),
        backgroundBubble.leadingAnchor.constraint(equalTo: Label.leadingAnchor, constant: 0),
        backgroundBubble.bottomAnchor.constraint(equalTo: Label.bottomAnchor, constant: 0),
        backgroundBubble.trailingAnchor.constraint(equalTo: Label.trailingAnchor, constant: 0)
    ]
    NSLayoutConstraint.activate(constraints)
}

The problem is that now the bubble view is sitting in front of the content:

enter image description here

I tried to move it back with:

sendSubviewToBack(backgroundBubble)

but then the yellow bubbleView disappears altogether.

How do I move the bubbleView behind the content of the prototype cell?


Solution

  • The content of a cell should basically always be added to its contentView. In this case, you may use contentView.insertSubview(backgroundBubble, at: 0) to add it as the first view in the hierarchy stack