I am iterating values and add them to a container UIView.
for value in bla {
// Create a new label
let labelHashtag = UILabelBadge()
labelHashtag.backgroundColor = .white
labelHashtag.frame.size.width = labelHashtag.intrinsicContentSize.width tagPadding
labelHashtag.frame.size.height = tagHeight
labelHashtag.layer.cornerRadius = labelHashtag.layer.frame.size.height / 2
labelHashtag.topInset = 2
labelHashtag.bottomInset = 2
labelHashtag.rightInset = 6
labelHashtag.leftInset = 6
labelHashtag.textAlignment = .center
// !!! Here I am trying to add an UIView and send it back !!!
let bla = UIView()
bla.frame = labelHashtag.bounds
bla.backgroundColor = .red
labelHashtag.addSubview(bla)
labelHashtag.sendSubviewToBack(bla)
Container.addSubview(labelHashtag)
}
It also does not work when I use insertSubview at: 0. It will stay on the top of my UILabel.
How can I add an UIView and send it back?
CodePudding user response:
When you add subview on UILabel means that UILabel is the root and all subviews will on the front of root view.
From your question, there are two approaches to achieve that.
First one, create a root UIView and add your UILabel and UIView into
for value in bla {
let rootUIView = UIView()
// Create a new label
let labelHashtag = UILabelBadge()
labelHashtag.backgroundColor = .white
labelHashtag.frame.size.width = labelHashtag.intrinsicContentSize.width tagPadding
labelHashtag.frame.size.height = tagHeight
labelHashtag.layer.cornerRadius = labelHashtag.layer.frame.size.height / 2
labelHashtag.topInset = 2
labelHashtag.bottomInset = 2
labelHashtag.rightInset = 6
labelHashtag.leftInset = 6
labelHashtag.textAlignment = .center
// !!! Here I am trying to add an UIView and send it back !!!
let backgroundView = UIView()
backgroundView.frame = labelHashtag.bounds
backgroundView.backgroundColor = .red
rootUIView.addSubview(labelHashtag)
rootUIView.addSubview(backgroundView)
rootUIView.sendSubviewToBack(backgroundView)
Container.addSubview(rootUIView)
}
Second one, make your UIView as a root and add your custom UILabel into it
for value in bla {
// Create a new label
let labelHashtag = UILabelBadge()
labelHashtag.backgroundColor = .white
labelHashtag.frame.size.width = labelHashtag.intrinsicContentSize.width tagPadding
labelHashtag.frame.size.height = tagHeight
labelHashtag.layer.cornerRadius = labelHashtag.layer.frame.size.height / 2
labelHashtag.topInset = 2
labelHashtag.bottomInset = 2
labelHashtag.rightInset = 6
labelHashtag.leftInset = 6
labelHashtag.textAlignment = .center
// !!! Here I am trying to add an UIView and send it back !!!
let backgroundView = UIView()
backgroundView.frame = labelHashtag.bounds
backgroundView.backgroundColor = .red
backgroundView.addSubview(labelHashtag)
Container.addSubview(backgroundView)
}