Ios 如何以编程方式将UILabel替换为UIView

Ios 如何以编程方式将UILabel替换为UIView,ios,swift,uiview,uilabel,Ios,Swift,Uiview,Uilabel,我有一个UILabel,它嵌套在StackView中,我需要创建一个UIView,它在屏幕上占据与UILabel完全相同的位置,然后隐藏UILabel(这是应用程序的高级部分,因此如果是免费版本,我需要用锁定图标替换数据)。下面的代码创建了视图,但它的位置远位于标签所在位置的右下角。我怎样才能完成我想做的事情 let testView = UIView() testView.frame = CGRect(x: hrrLabel.fr

我有一个UILabel,它嵌套在StackView中,我需要创建一个UIView,它在屏幕上占据与UILabel完全相同的位置,然后隐藏UILabel(这是应用程序的高级部分,因此如果是免费版本,我需要用锁定图标替换数据)。下面的代码创建了视图,但它的位置远位于标签所在位置的右下角。我怎样才能完成我想做的事情

                let testView = UIView()
                testView.frame = CGRect(x: hrrLabel.frame.origin.x, y: hrrLabel.frame.origin.y, width: hrrLabel.frame.width, height: hrrLabel.frame.height)
                testView.backgroundColor = UIColor.red
                hrrLabel.isHidden = true
                hrrLabel.addSubview(testView)

只需将
testView
放在
hrrLabel
的边界中即可。(假设要放在顶部的视图是
testView
——不完全确定哪个视图应该是哪个视图)


查找
CGRect.bounds
CGRect.frame
之间的差异,这将使创建子视图变得更加容易。

标签是如何创建的?它有约束吗?为什么不让视图成为标签的子视图,其框架等于标签边界?这样就可以覆盖标签,不会造成任何伤害。谢谢,这很有效,我假设isHidden行不起作用,因为隐藏视图也会隐藏其子视图。但是,我刚刚更改了
hrrLabel.text=“
并获得了相同的效果
let testView = UIView()
testView.frame = hrrLabel.bounds //Bounds here, not frame
testView.backgroundColor = UIColor.red
hrrLabel.isHidden = true
hrrLabel.addSubview(testView)

//Hide view without hiding subviews
hrrLabel.backgroundColor = hrrLabel.backgroundColor.withAlphaComponent(alpha: 0)
//hrrLabel.isHidden = true