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

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):请注意,在 viewDidLoadviewWillAppear/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.

这篇关于出现异常:“无法使用未准备好约束的视图层次结构设置布局"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Why local notification is not firing for UNCalendarNotificationTrigger(为什么没有为UNCalendarNotificationTrigger触发本地通知)
iOS VoiceOver functionality changes with Bundle Identifier(IOS画外音功能随捆绑包标识符而变化)
tabbar middle tab out of tabbar corner(选项卡栏中间的选项卡角外)
Pushing UIViewController above UITabBar(将UIView控制器推送到UITabBar上方)
Dropbox Files.download does not start when number of files in folder is gt; 1000(当文件夹中的文件数为1000时,Dropbox Files.Download不会启动)
How can I sync two flatList scroll position in react native(如何在本机Reaction中同步两个平面列表滚动位置)