EDIT - I fixed it. See answer.
I'm trying to learn how to create constraints programmatically. I tried to constrain a UILabel
to the top of the screen, using this code, in viewDidLoad
:
override func viewDidLoad() {
super.viewDidLoad()
//the variable label already exists. I make a UILabel.
label = UILabel()
label.text = "Hello"
label.backgroundColor = UIColor(red: 1, green: 1, blue: 0, alpha: 1)
//I add the label to the ViewController
view.addSubview(label)
//I use an array of constraints because I will make more later.
let constraints : [NSLayoutConstraint] = [
NSLayoutConstraint(item: label, attribute: .top, relatedBy: .equal, toItem: topLayoutGuide, attribute: .bottom, multiplier: 1.0, constant: 0.0)
]
view.addConstraints(constraints)
}
When I run my app, I get an error beginning with:
[LayoutConstraints] Unable to simultaneously satisfy constraints.
My intended equation for the constraint was:
label.top = 1.0 * topLayoutGuide.bottom + 0.0
When I created what seems to be an identical constraint with Interface Builder, it worked. However, it doesn't when I try to do it programatically. What's wrong with what I'm doing, and how can I programmatically make a constraint using NSLayoutConstraint
that will pin my Label to the top of the screen right below the status bar?
My sources:
Apple - Anatomy of a Constraint