如何使 UILabel 在 Swift 中居中?

How to center UILabel in Swift?

我正在尝试使一些文本居中,但它似乎不起作用。

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.
    }

}

这是我正在使用的代码,但这是我得到的:

它不在屏幕中央。有人可以告诉我我做错了什么吗?

要使 UILabel 居中,只需添加此行

x 和 y:

title.center = self.view.center

x:

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

y:

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

实际上,您所做的是将 UILabel 中的文本居中。您要做的是将标签居中。为此,您可以这样做:

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

如果你想水平居中,你可以这样做:

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

此外,如果您想将标签的 x 和 y 值居中,您可以执行以下操作:

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

自动布局

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

1。禁用 translatesAutoresizing

titleLabel.translatesAutoresizingMaskIntoConstraints = false

2。添加 CenterX 和 CenterY 约束

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

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

3。将 UILabel 的文本对齐设置为居中

titleLabel.textAlignment = .center

SWIFT 4

这对我有用,而且似乎更有前途。这也适用于多行标签。

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
}

代码 swift 3/4/5

在 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!)