Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centering UILabel not working?

Tags:

ios

swift

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?

like image 774
MarksCode Avatar asked Jan 05 '23 00:01

MarksCode


1 Answers

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

like image 116
kamwysoc Avatar answered Jan 07 '23 13:01

kamwysoc