首页 > 解决方案 > 如何以编程方式用 UIView 替换 UILabel

问题描述

我有一个嵌套在 StackView 内的 UILabel,我需要创建一个 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)

标签: iosswiftuiviewuilabel

解决方案


只需将testView放在您hrrLabel的范围内即可。(假设您要放置在 TOP 上的testView视图是 - 不完全确定哪个视图应该是哪个)。

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

CGRect.bounds查找和之间的区别CGRect.frame将使创建子视图更加容易。


推荐阅读