更新stackview约束会导致崩溃:"视图层次结构没有为约束做好准备"

时间:2017-01-07 07:59:24

标签: ios swift ipad autolayout uistackview

当我尝试在 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.

enter image description here enter image description here

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

enter image description here

1 个答案:

答案 0 :(得分:1)

请注意崩溃消息:

  

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

这意味着stackView尚未成为contentView的子视图(反之亦然)。