Search code examples
iosswiftuiviewuilabel

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). 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)

Solution

  • Simply place the testView in your hrrLabel's bounds. (Assuming the view you want to place on TOP is the testView -- not entirely sure which view is suppose to be which).

    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.