所以我想以编程方式将 UILabel 在视图中水平和垂直居中。我关注了这个主题,但它不起作用。我怎样才能做到这一点?
p/s:这是我的代码:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let noDataLabel = UILabel()
noDataLabel.text = "No data :("
noDataLabel.textColor = UIColor.redColor()
noDataLabel.font = UIFont.systemFontOfSize(20)
noDataLabel.sizeToFit()
self.view.addSubview(noDataLabel)
NSLayoutConstraint(item: noDataLabel, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1.0, constant: 0.0).active = true
NSLayoutConstraint(item: noDataLabel, attribute: .CenterY, relatedBy: .Equal, toItem: self.view, attribute: .CenterY, multiplier: 1.0, constant: 0.0).active = true
}
}
Run Code Online (Sandbox Code Playgroud)