ios 出现异常:“无法使用未准备好约束的视图层次结构来设置布局”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26349234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 03:10:49  来源:igfitidea点击:

Getting Exception: "Impossible to set up layout with view hierarchy unprepared for constraint"

iosswiftautolayout

提问by mustafa

In my storyboard application I try to add extra UITextFieldto interface. But I get the exception that title says. I use SwiftAutoLayoutlibrary. Here is my code:

在我的故事板应用程序中,我尝试UITextField向界面添加额外内容。但我得到了标题所说的例外。我使用SwiftAutoLayout库。这是我的代码:

// MARK: - IBOutlets

@IBOutlet weak var passwordTextField: UITextField!

// MARK: - Properties

let userIdTextField = UITextField()

// MARK: - Lifecycle

override func viewDidLoad() {
    super.viewDidLoad()

    self.passwordTextField.keyboardType = .NumberPad

    if getCurrentUserId() == nil {
        self.view.addSubview(userIdTextField)
        userIdTextField.setTranslatesAutoresizingMaskIntoConstraints(false)
        self.view.addConstraints([userIdTextField.al_leading == passwordTextField.al_leading,
            userIdTextField.al_trailing == passwordTextField.al_trailing,
            userIdTextField.al_top == passwordTextField.al_bottom + 8])
        userIdTextField.placeholder = "Enter User Id..."
    }
}

回答by knuku

Try adding passwordTextFieldto its superview before binding any constraints to it.

passwordTextField在绑定任何约束之前尝试添加 到它的超级视图。



UPD(thanks @vmeyer and @MacMark): please notice that it's safer to add constraints not in viewDidLoador viewWillAppear/viewDidAppearbut in updateViewConstraintsor viewWillLayoutSubviewssince the view hierarchy might be unprepared for this operation.

UPD(感谢@vmeyer和@MacMark):请注意,它的安全不加限制viewDidLoadviewWillAppear/viewDidAppearupdateViewConstraintsviewWillLayoutSubviews因为视图层次结构可能是准备好执行这项操作。

回答by vmeyer

I suggest you to not add constraints in viewDidLoad, because the view hierarchy is set, but not constraints. You should prefer updateViewConstraintsor viewWillLayoutSubviews

我建议您不要在 viewDidLoad 中添加约束,因为设置了视图层次结构,而不是约束。您应该更喜欢updateViewConstraintsviewWillLayoutSubviews

回答by Gurjinder Singh

You are trying to adding constraint to view which is not added/created in current view hierarchy. First add view then apply constraint.

您正在尝试向当前视图层次结构中未添加/创建的视图添加约束。首先添加视图然后应用约束。

回答by Aakash Gupta

Please add the view to superview before adding constraints for the view in superview.

请先将视图添加到超级视图,然后再为超级视图中的视图添加约束。

superView?.addSubview(view) superView?.addConstraints([topConstraint,leftConstraint,bottomConstraint,rightConstraint])

superView?.addSubview(view) superView?.addConstraints([topConstraint,leftConstraint,bottomConstraint,rightConstraint])