如何以编程方式用 UIView 替换 UILabel
How to replace a UILabel with a UIView programmatically
我有一个嵌套在 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)
只需将 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
之间的区别,这将使创建子视图更加容易。
我有一个嵌套在 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)
只需将 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
之间的区别,这将使创建子视图更加容易。