Error: Thread 1: "Impossible to set up layout with view hierarchy unprepared for constraint." when using auto layout

Error: Thread 1: "Impossible to set up layout with view hierarchy unprepared for constraint." when using auto layout

我的代码在下面,我不知道是什么导致出现这个错误。一些想法?

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

我已经尝试在 'viewDidLoad()' 之外调用 'lbl1values()',但我得到了完全相同的错误。

这应该可以满足您的需要。在设置约束之前,您需要先将视图添加为子视图。我在下面添加了一个清晰的示例。

您还应该在标签上设置 translatesAutoresizingMaskIntoConstraints 属性 这意味着系统不会创建一组复制视图自动调整掩码指定的行为的约束。

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),
    ])
}