How to center UILabel in Swift?

Auto Layout

To make your app future proof rather use auto layout anchors instead of setting the frame.

1. Disable translatesAutoresizing

titleLabel.translatesAutoresizingMaskIntoConstraints = false

2. Add CenterX & CenterY constraints

titleLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true

titleLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

3. Set UILabel's text alignment to center

titleLabel.textAlignment = .center

Preview


To center a UILabel just add this row

x and y:

title.center = self.view.center

x:

title.center.x = self.view.center.x

y:

title.center.y = self.view.center.y

Actually what you are doing is centering the text inside the UILabel. What you want to do is to center the label. To do it you can do:

title.frame.origin = CGPoint(x: x, y: y)

If you want to center the horizontal you can do:

title.frame.origin = CGPoint(x: self.view.frame.width / 2, y: yValue)

Also if you want to center the x and y value of your label you can do:

title.frame.origin = CGPoint(x: self.view.frame.width / 2, y: self.view.frame.height / 2)