将UIView添加到自定义UILabel时,sendSubviewToBack不起作用



我正在迭代值,并将它们添加到容器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)
}

当我在以下位置使用insertSubview时,它也不起作用:0。它将保留在我的UILabel顶部。

如何添加UIView并将其发送回?

当您在UILabel上添加子视图时,意味着UILabel是根,所有子视图都将位于根视图的前面。

从你的问题来看,有两种方法可以实现这一点。

首先,创建一个根UIView,并将您的UILabel和UIView添加到中

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)
}

第二,将UIView作为根目录,并将自定义UILabel添加到中

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)
}

相关内容

  • 没有找到相关文章

最新更新