我在垂直 UIStackView 中添加了一些 arrangedSubView。 我想通过点击某个按钮来增加内部排列的一个 subview 的高度。
尝试在 subview 和主视图上添加 layoutIfNeeded。 它不工作。
我正在增加 subview 的高度,如下所示:
addConstraints([self.heightAnchor.constraint(equalToConstant: 100)])
layoutIfNeeded()
sizeToFit()
layoutSubviews()
最佳答案
我认为问题在于您正在尝试向 View 添加新约束,但您没有停用 heightAnchor 的现有约束。
您可以在添加新约束之前将现有高度约束的 isActive 属性设置为 false,或者简单地将现有高度约束的常量设置为新值。
您可以为约束提供一个标识符,稍后您可以使用它来获取该特定约束并更改其属性。
如果我是你,我会在我的代码中添加以下两个扩展:
extension UIView {
func getConstraint(withIndentifier indentifier: String) -> NSLayoutConstraint? {
return self.constraints.filter { $0.identifier == indentifier }.first
}
}
extension NSLayoutConstraint {
func activate(withIdentifier identifier: String) {
self.identifier = identifier
self.isActive = true
}
}
示例用法:
// When you create the constraint:
subview.heightAnchor.constraint(equalToConstant: 100).activate(withIdentifier: "THE")
// When you want to change the constant:
if let filteredConstraint = subview.getConstraint(withIndentifier: "THE") {
filteredConstraint.constant = 500
}
如果你想要动画,只需在更改约束后立即添加以下代码:
UIView.animate(withDuration: 0.5) {
self.view.layoutIfNeeded()
}
我相信这会奏效,否则请告诉我。
更新
当你像这样设置约束时:
self.myStackView.topAnchor.constraint(equalTo: someView.bottomAnchor , constant: 20).activate(withIdentifier: "topAnchor")
约束实际上既不属于myStackView
也不属于someView
,而是它们的父 View 。虽然matt's answer是正确的,我个人更喜欢Kh_khan's answer在评论中:
self.myStackView.superView?.getConstraint(withIndentifier: "topAnchor")
让我知道它是否有效。
关于ios - 如何在运行时增加堆栈 View 的特定 subview 的高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57102565/