如何在Swift中居中UILabel?

41

我试图让一些文字居中,但似乎没有成功。

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

}

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

输入图像描述

它没有居中显示在屏幕上。有人能告诉我我做错了什么吗?

5个回答

79

要将UILabel居中,只需添加以下行

x和y:

title.center = self.view.center

x:

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

y:

->

y:

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

那很好!但是如果我只想在X轴上居中呢? - elpita
1
只需添加.x title.center.x = self.view.center.x 用于y: title.center.y = self.view.center.y - Rashwan L
我正在通过tableView的viewForHeaderInSection委托方法自定义我的标题视图,但它并没有像你所提到的那样将标签居中。我设置了框架,如下:label.frame = CGRect(x: self.view.frame.size.width/2, y: self.view.bounds.height/2, width: 80, height: 20),并在它之前添加了你的代码行。 - Usama bin Attique
@UsamabinAttique,如果我理解你的问题正确的话,尝试设置tableView的中心点。tableView.center.ytableView.center.x - Rashwan L
是的,这是一个TableView,但我正在通过我提到的方法自定义标题。如果您不自定义标题,您可以返回高度和要在其中显示的任何字符串。在我的情况下,它仍然是一个标签,但视图稍微大一些,颜色方案也不同,并且委托方法返回一个UIView,所以我首先初始化它,如let view = UIView(),然后在其中编程设置标签。但它没有起作用。 - Usama bin Attique
@RashwanL请也看一下这个问题,如果你有时间的话。我会非常感激你。https://stackoverflow.com/questions/46361686/how-to-restrict-button-click - Usama bin Attique

39

自动布局

为了使您的应用程序具有未来的可靠性,建议使用自动布局锚点而不是设置框架。

1. 禁用translatesAutoresizingMaskIntoConstraints属性

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

预览


这是最好且更安全的答案。由于这只支持 iOS 9,对于低版本,您可以使用: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

11

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
}

11

实际上你正在对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)

我尝试了这个,但是出现了错误,提示“类型为UILABEL的值没有成员'position'”。 - elpita

3

适用于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!)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接