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:
Is it an iOS bug? Or how can I change UILabel.text
without overlapping?
2
Answers
To fix this issue replace
label.backgroundColor = nil
withlabel.backgroundColor = .clear
. You should not usenil
forUILabel.backgroundColor
.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.