Home > Software design >  Error: Thread 1: "Impossible to set up layout with view hierarchy unprepared for constraint.&qu
Error: Thread 1: "Impossible to set up layout with view hierarchy unprepared for constraint.&qu

Time:10-03

My code is down below, and I don't know what makes this error appear. Some ideas?

Thread 1: "Impossible to set up layout with view hierarchy unprepared for constraint."
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        view.backgroundColor = .blue
        lbl1values()
    }
    
    
    
    
    let lbl1 = UILabel()
    
    
    func lbl1values(){
        lbl1.addConstraint(NSLayoutConstraint(item: lbl1,
                                              attribute: .leading,
                                              relatedBy: .equal,
                                              toItem: view,
                                              attribute: .trailing,
                                              multiplier: 1.0,
                                              constant: 8.0))
    
        lbl1.addConstraint(NSLayoutConstraint(item: lbl1,
                                              attribute: .top,
                                              relatedBy: .equal,
                                              toItem: view,
                                              attribute: .bottom,
                                              multiplier: 1.0,
                                              constant: -8.0))
        
        view.addSubview(lbl1)
    }
}

I have already tried to call 'lbl1values()' outside of 'viewDidLoad()', but I get the exact same error.

CodePudding user response:

This should work as you need. You need to add the view as a subview first before you set its constraints. I've added a clear example below.

You should also set the translatesAutoresizingMaskIntoConstraints property on the label this means the system won't create a set of constraints that duplicate the behaviour specified by the view’s autoresizing mask.

private let label = UILabel(frame: CGRect())

override func viewDidLoad() {
    view.backgroundColor = .blue

    setUp(label: label)
    view.addSubview(label)

    setUpConstraints()
}

private func setUp(label: UILabel) {
    label.translatesAutoresizingMaskIntoConstraints = false
}

private func setUpConstraints() {
    NSLayoutConstraint.activate([
        label.topAnchor.constraint(equalTo: view.topAnchor),
        label.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 8),
        label.trailingAnchor(equalTo: view.trailingAnchor, constant: -8),
        label.bottomAnchor.constraint(equalTo: view.bottomAnchor),
    ])
}
  • Related