Getting Exception: quot;Impossible to set up layout with view hierarchy unprepared for constraintquot;(出现异常:“无法使用未准备好约束的视图层次结构设置布局)
问题描述
在我的故事板应用程序中,我尝试向界面添加额外的 UITextField.但我得到了标题所说的例外.我使用 SwiftAutoLayout 库.这是我的代码:
In my storyboard application I try to add extra UITextField to interface. But I get the exception that title says. I use SwiftAutoLayout library. Here is my code:
// 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..."
}
}
推荐答案
在绑定任何约束之前尝试将 passwordTextField 添加到其父视图.
Try adding passwordTextField to its superview before binding any constraints to it.
UPD(感谢 @vmeyer 和 @MacMark):请注意,在 viewDidLoad 或 viewWillAppear/viewDidAppear 但在 updateViewConstraints 或 viewWillLayoutSubviews 因为视图层次结构可能没有为此操作做好准备.
UPD (thanks @vmeyer and @MacMark): please notice that it's safer to add constraints not in viewDidLoad or viewWillAppear/viewDidAppear but in updateViewConstraints or viewWillLayoutSubviews since the view hierarchy might be unprepared for this operation.
这篇关于出现异常:“无法使用未准备好约束的视图层次结构设置布局"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:出现异常:“无法使用未准备好约束的视图层次结构设置布局"
基础教程推荐
- 如何将图像从一项活动发送到另一项活动? 2022-01-01
- iOS - UINavigationController 添加多个正确的项目? 2022-01-01
- Xcode UIView.init(frame:) 只能在主线程中使用 2022-01-01
- navigationItem.backBarButtonItem 不工作?为什么上一个菜单仍然显示为按钮? 2022-01-01
- Play 商店的设备兼容性问题 2022-01-01
- Android Volley - 如何动画图像加载? 2022-01-01
- SwiftUI-ScrollViewReader的ScrollTo不滚动 2022-01-01
- 如何比较两个 NSDate:哪个是最近的? 2022-01-01
- UIImage 在开始时不适合 UIScrollView 2022-01-01
- 为什么姜饼模拟器方向卡在应用程序中? 2022-01-01
