【问题标题】:How to replace a UILabel with a UIView programmatically如何以编程方式用 UIView 替换 UILabel
【发布时间】:2020-07-01 03:49:13
【问题描述】:

我有一个嵌套在 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)

【问题讨论】:

  • 标签是如何创建的?有限制吗?
  • 为什么不让视图成为标签的子视图,其框架等于标签边界?这样它就可以覆盖标签并且不会造成任何伤害。

标签: ios swift uiview uilabel


【解决方案1】:

只需将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.boundsCGRect.frame 之间的区别,这将使创建子视图更加容易。

【讨论】:

  • 谢谢这很好用,我假设 isHidden 行不起作用,因为隐藏视图也会隐藏它的子视图。不过我只是换了hrrLabel.text = " ",也达到了同样的效果。
  • 查看编辑隐藏视图而不隐藏子视图
猜你喜欢
  • 2020-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-21
  • 1970-01-01
  • 1970-01-01
  • 2018-05-13
相关资源
最近更新 更多