使用 UILabel 以编程方式自动布局不起作用

Đin*_*iếu 0 uilabel ios autolayout swift

所以我想以编程方式将 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)

Pra*_*tha 5

将其添加到您的代码中:

 noDataLabel.translatesAutoresizingMaskIntoConstraints = false
Run Code Online (Sandbox Code Playgroud)

来自苹果文档:

默认情况下,视图上的自动调整大小蒙版会产生完全确定视图位置的约束。这允许自动布局系统跟踪手动控制布局的视图框架(例如,通过 -setFrame:)。当您选择通过添加自己的约束来使用自动布局来定位视图时,必须将此属性设置为“否”。IB 将为您做这件事。