Search code examples
iosxcodeswiftvisual-format-language

VFL constraints in swift: Crashes due to no superview


I'm trying to do a simple layout programmatically and I'm missing something simple, or have something out of place, I think. The following ViewController should center the label in the super view. However, it crashes with this trimmed message: The view hierarchy is not prepared for the constraint ... When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled... View not found in container hierarchy: ... That view's superview: NO SUPERVIEW The other SO questions with this error message are using nibs for the most part, and I'm tring to avoid that, or use Obj-C instead of swift. This question deals with the topic a bit but is a bit old.

Can anyone point me in the right direction?

class ViewController: UIViewController {
let label1 = UILabel() as UILabel

func layoutView(){

    label1.text = "Click to see device configuration"
    label1.setTranslatesAutoresizingMaskIntoConstraints(false)
    view.addSubview(label1)
    let viewsDictionary = ["label1":label1]

    let label1_H:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label1]-|",
        options: NSLayoutFormatOptions(0),
        metrics: nil,
        views: viewsDictionary)

    let label1_V:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("V:|-[label1]-|",
        options: NSLayoutFormatOptions(0),
        metrics: nil, views:
        viewsDictionary)

    label1.addConstraints(label1_H) // Comment these 2 lines and it runs, but
    label1.addConstraints(label1_V) // of course the label is upper left

}

override func viewDidLoad() {
    super.viewDidLoad()
    layoutView()
}
}

Solution

  • Those constraints are made between the label and its superview. The constraints should be added to that superview, not to the label.