更新 UIStackView 内部视图的高度约束

Updating the Height Constraint of a View Inside of a UIStackView

目前,我设置了我稍后添加到堆栈视图的一个视图的高度和宽度约束,如下所示:(供您参考,productsTable 是一个 UITableView。)

    productsTable.heightAnchor.constraintEqualToConstant(tableHeight).active = true
    productsTable.widthAnchor.constraintEqualToConstant(stackWidth).active = true
    stackView.insertArrangedSubview(productsTable, atIndex: productsTableIndex)

稍后,在 ViewWillAppear 中,我想按如下方式更改 productsTable 的高度:

productsTable.heightAnchor.constraintEqualToConstant(newHeight).active = true.

尽管如此,table 视图在 (changing/updating) ViewWillAppear 中的约束后仍保持相同大小。我有什么地方做错了或者可以做不同的事情来达到预期的效果吗?

您需要保留对您第一次创建的高度限制的引用。

let heightConstraint = productsTable.heightAnchor.constraintEqualToConstant(tableHeight)
heightConstraint.active = true

稍后,在 viewWillAppear() 中,您将能够直接将此约束的常量属性设置为 newHeight。

heightConstraint.constant = newHeight