如何在Swift中使用UILabel?
我试图集中一些文字,但我似乎并没有工作。
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里面input文字。 你想要做的是把中心de标签。 要做到这一点,你可以这样做:
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)