I have to programmatically center my UILabel so that the center of its text is in the center of the screen at all times. However, I keep getting it so the left hand side seems horizontally centered instead:
I'm using the following code to do this:
let label = UILabel()
label.center = self.view.center
label.textAlignment = .center
self.view.addSubview(label)
So I want the label to have equal margins horizontally, and the text within to be centered as well. Note that I have to do this programatically unfortunetely. Can anybody help me see what I'm doing wrong?
Just set centerXAnchor
and centerYAnchor
programmatically:
view.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
label.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant:0).isActive = true
label.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant:0).isActive = true
label.widthAnchor.constraint(equalToConstant: 50.0).isActive = true
This should help you
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With