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
Getting Exception: "Impossible to set up layout with view hierarchy unprepared for constraint"
提问by mustafa
In my storyboard application I try to add extra UITextField
to 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 passwordTextField
to 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 viewDidLoad
or viewWillAppear
/viewDidAppear
but in updateViewConstraintsor viewWillLayoutSubviewssince the view hierarchy might be unprepared for this operation.
UPD(感谢@vmeyer和@MacMark):请注意,它的安全不加限制viewDidLoad
或viewWillAppear
/viewDidAppear
但 updateViewConstraints或viewWillLayoutSubviews因为视图层次结构可能是准备好执行这项操作。
回答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 中添加约束,因为设置了视图层次结构,而不是约束。您应该更喜欢updateViewConstraints或viewWillLayoutSubviews
回答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])