MarksCode MarksCode - 1 year ago 113
Swift Question

Centering UILabel not working?

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.textAlignment = .center

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?

Answer Source

Just set centerXAnchor and centerYAnchor programmatically:

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download