-1

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

Apple - Programmatically creating Constraints

StackOverflow - SWIFT | Adding constraints programmatically

Community
  • 1
  • 1
ostrichofevil
  • 749
  • 7
  • 19
  • Fwiw, if you're doing a lot of programmatic constrains, check out SnapKit or some other AutoLayout framework to make your life a million times easier. – brandonscript Sep 18 '16 at 03:43
  • @brandonscript I know, and I would rather use IB or something else, but I want to understand how to do it programmatically. – ostrichofevil Sep 18 '16 at 14:38

1 Answers1

-1

This can be fixed by setting translatesAutoresizingMaskIntoConstraints to be false, to avoid clashes with existing Mask Constraints:

label.translatesAutoresizingMaskIntoConstraints = false
ostrichofevil
  • 749
  • 7
  • 19