【问题标题】:Updating stackview constraints results in crash: "The view hierarchy is not prepared for the constraint"更新 stackview 约束会导致崩溃:“视图层次结构没有为约束做好准备”
【发布时间】:2017-05-22 00:20:25
【问题描述】:

当视图在 iPad 上改变方向时,我正尝试以编程方式更新堆栈视图中的约束。

默认情况下,视图的前导和尾随为 20pt(横向),但是,当它变为纵向时,我想将其更改为 8pt

(我无法添加尺寸限制类,因为设备当前在 iPad 上,并且尺寸类都是 wRhR。)

目前我只是通过单击以下按钮来更改约束:

    let leadingConstraint = NSLayoutConstraint(item: stackView, attribute: .leading, relatedBy: .equal, toItem: contentView, attribute: .leading, multiplier: 1, constant: 8)
    let trailingConstraint = NSLayoutConstraint(item: contentView, attribute: .trailing, relatedBy: .equal, toItem: stackView, attribute: .trailing, multiplier: 1, constant: 8)
    let topConstraint = NSLayoutConstraint(item: stackView, attribute: .top, relatedBy: .equal, toItem: topLabel, attribute: .bottom, multiplier: 1, constant: 160)

    // remove old constraints
    stackView.removeConstraints(stackView.constraints)
    stackView.addConstraints([leadingConstraint, trailingConstraint, topConstraint])

    stackView.updateConstraints()

导致崩溃:

The view hierarchy is not prepared for the constraint: <NSLayoutConstraint:0x618000092520 H:|-(20)-[UIStackView:0x7fbfcbd0bf90] (inactive, names: '|':UIView:0x7fbfcbe04150 )> When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled. Break on -[UIView(UIConstraintBasedLayout) _viewHierarchyUnpreparedForConstraint:] to debug.

编辑:这是我的界面构建器的布局:

【问题讨论】:

    标签: ios swift ipad autolayout uistackview


    【解决方案1】:

    注意崩溃消息:

    添加到视图时,约束项必须是该视图(或视图本身)的后代。

    这意味着stackView 还不是contentView 的子视图(反之亦然)。

    【讨论】:

    • 这很奇怪。尽管stackView 位于contentView 内部,但在界面生成器中。这不是表明stackView 是那个时候的子视图吗?编辑原始帖子以显示我的界面构建器布局
    • 有没有办法让它进入子视图?从那以后我就没有运气了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-19
    相关资源
    最近更新 更多