简体   繁体   English

如何以编程方式用 UIView 替换 UILabel

[英]How to replace a UILabel with a UIView programmatically

I have a UILabel that is nested inside of a StackView, and I am needing to create a UIView that will take up the exact same position on the screen as the UILabel did, and then hide the UILabel (this is a premium portion of an app, so if it's the free version I need to replace the data with a lock icon).我有一个嵌套在 StackView 内部的 UILabel,我需要创建一个 UIView,它将在屏幕上占据与 UILabel 完全相同的位置,然后隐藏 UILabel(这是应用程序的高级部分) ,所以如果它是免费版本,我需要用锁图标替换数据)。 My code below creates the view but it's positioning is far to the bottom right of where the label is.我下面的代码创建了视图,但它的位置远在标签所在位置的右下角。 How can I accomplish what I'm trying to do?我怎样才能完成我想要做的事情?

                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)

Simply place the testView in your hrrLabel 's bounds.只需将testView放在hrrLabel的边界中。 (Assuming the view you want to place on TOP is the testView -- not entirely sure which view is suppose to be which). (假设您想放在 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

Lookup the difference between CGRect.bounds and CGRect.frame and it will make creating subviews much easier.查找CGRect.boundsCGRect.frame之间的区别,它将使创建子视图更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM