如何在Swift中心UILabel?

问题描述:

我正试图将一些文字放在中心,但我似乎没有工作。

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:

它不是屏幕的中心。有人能告诉我我做错了什么吗?

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

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

To center a UILabel just add this row

x和y:

title.center = self.view.center

x:

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

y:

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