How to center UILabel in Swift?
Asked Answered
C

5

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?

Cadel answered 7/1, 2016 at 1:33 Comment(0)
L
80

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
Lowrie answered 7/1, 2016 at 1:38 Comment(6)
that work! But what if i want to only center it in the X axis?Cadel
Just add .x title.center.x = self.view.center.xfor y: title.center.y = self.view.center.yLowrie
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.Determination
@UsamabinAttique, try to set the center of the tableView instead if I understand your question right. tableView.center.y and tableView.center.xLowrie
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 workingDetermination
@RashwanL please have a look at this one as well. if you have time. I'd be grateful to you. #46362186Determination
W
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

Winona answered 3/7, 2018 at 10:14 Comment(1)
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 = trueMontagnard
J
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)
Jetport answered 7/1, 2016 at 1:41 Comment(1)
I tried this but I get the error saying "value of type UILABEL has no member 'position'"Cadel
P
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
}
Penguin answered 30/8, 2018 at 17:51 Comment(0)
A
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!)
Adder answered 5/9, 2019 at 4:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.