Đinh Quang Hiếu Đinh Quang Hiếu - 4 months ago 11
Swift Question

Autolayout programmatically with UILabel doesn't work

So I want to center horizontal and vertical a UILabel in my View programmatically. I follow this topic but it doesn't work. How can I do that?

p/s: this is my code:

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

Answer

Add this to your code:

 noDataLabel.translatesAutoresizingMaskIntoConstraints = false

From apple documentation:

By default, the autoresizing mask on a view gives rise to constraints that fully determine the view's position. This allows the auto layout system to track the frames of views whose layout is controlled manually (through -setFrame:, for example). When you elect to position the view using auto layout by adding your own constraints, you must set this property to NO. IB will do this for you.

Comments