41

I'm trying to center some text but I it doesn't seem to be working.

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.


        let title = UILabel()
        title.text = "Some Sentence"
        title.numberOfLines = 0
        title.frame = CGRectMake(self.view.bounds.size.width/2,50,self.view.bounds.size.width, self.view.bounds.size.height) // x , y, width , height
        title.textAlignment = .Center
        title.sizeToFit()
        title.backgroundColor = UIColor.redColor()
        self.view.addSubview(title)

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

That is the code that I'm using but this is what I get:

enter image description here

It's not center to the screen. Can someone tell me what am I doing wrong?

LuLuGaGa
  • 13,089
  • 6
  • 49
  • 57
elpita
  • 1,085
  • 3
  • 12
  • 13

5 Answers5

79

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
Rashwan L
  • 38,237
  • 7
  • 103
  • 107
  • that work! But what if i want to only center it in the X axis? – elpita Jan 07 '16 at 01:41
  • 1
    Just add .x `title.center.x = self.view.center.x`for y: `title.center.y = self.view.center.y` – Rashwan L Jan 07 '16 at 01:43
  • I am customizing my header view via delegate method of tableView `viewfForHeaderInSection` and it doesn't center the label like you've mentioned. I am setting the frame like label.frame = CGRect(x: self.view.frame.size.width/2, y: self.view.bounds.height/2, width: 80, height: 20) and i've added your lines before it. – Usama bin Attique Sep 16 '17 at 19:30
  • @UsamabinAttique, try to set the center of the tableView instead if I understand your question right. `tableView.center.y` and `tableView.center.x` – Rashwan L Sep 17 '17 at 07:08
  • yes its a tableview but i am customizing the header via the method i've mentioned. if you dont customize the header you can just return the height and whatever string you want to display in it. in my case its still a label but the view is a bit larger and the color scheme is different and the delegate method returns a UIView so i am initializing it first like let view = UIView() and then setting up a label programatically in it. and its not working – Usama bin Attique Sep 18 '17 at 05:11
  • @RashwanL please have a look at this one as well. if you have time. I'd be grateful to you. https://stackoverflow.com/questions/46361686/how-to-restrict-button-click – Usama bin Attique Sep 22 '17 at 10:53
39

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

8HP8
  • 1,720
  • 3
  • 16
  • 15
  • This is the best and safer answer. Since this is just supported from iOS 9, for lower version you can use: `NSLayoutConstraint(item: titleLabel, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0).isActive = true` `NSLayoutConstraint(item: titleLabel, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1, constant: 0).isActive = true` – rgkobashi Jul 27 '18 at 01:10
11

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)
11

SWIFT 4

This worked for me and seems more future proof. This also works for a multi-line label.

override func loadView() {
    self.view = UIView()

    let message = UILabel()
    message.text = "This is a test message that should be centered."
    message.translatesAutoresizingMaskIntoConstraints = false
    message.lineBreakMode = .byWordWrapping
    message.numberOfLines = 0
    message.textAlignment = .center

    self.view.addSubview(message)

    message.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
    message.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    message.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
}
Devbot10
  • 1,193
  • 18
  • 33
3

Code for swift 3/4/5

Paste below code after super.viewDidLoad()

var noDataLbl : UILabel?
noDataLbl = UILabel(frame: CGRect(x: 0, y: self.view.center.y, width: 290, height: 70))
noDataLbl?.textAlignment = .center
noDataLbl?.font = UIFont(name: "Halvetica", size: 18.0)
noDataLbl?.numberOfLines = 0
noDataLbl?.text = "Replace this with your text."
noDataLbl?.lineBreakMode = .byTruncatingTail
noDataLbl?.center = self.view.center
view.addSubview(noDataLbl!)
Community
  • 1
  • 1
vilas deshmukh
  • 389
  • 2
  • 5