skip to Main Content

I have a simple UIViewController with UILabel and UIButton:

class MyScreen: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .blue
        let values = ["AAA", "BBB", "CCC", "DDD"]
        var index = 0
        let label = UILabel(frame: .init(x: 100, y: 100, width: 100, height: 50))
        label.backgroundColor = nil
        label.textColor = .yellow
        view.addSubview(label)
        let button = UIButton(frame: .init(x: 100, y: 200, width: 100, height: 50))
        button.setTitle("Tap", for: .normal)
        button.addAction(.init(handler: { _ in
            label.text = values[index]
            index = (index + 1) % values.count
        }), for: .primaryActionTriggered)
        view.addSubview(button)
    }
}

As you can see I just change label.text on tap. However, the text is overlapping:
iPhone Simulator

Is it an iOS bug? Or how can I change UILabel.text without overlapping?

2

Answers


  1. Chosen as BEST ANSWER

    To fix this issue replace label.backgroundColor = nil with label.backgroundColor = .clear. You should not use nil for UILabel.backgroundColor.


  2. I think you want to make Label background color clear, so set to .clear or don’t set background is well.

    UIKit seems to change some value of views when drawing. If the label has no color (no something to fill contents), can set isOpaque = false to try.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search