MarksCode MarksCode - 18 days ago 5
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:

pic

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?

Answer

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