Ios 自动布局:如何创建折叠/展开动态视图swift 3/4

Ios 自动布局:如何创建折叠/展开动态视图swift 3/4,ios,swift,swift3,autolayout,Ios,Swift,Swift3,Autolayout,我有一个问题,我无法创建一个可以折叠其内容(可能是动态高度)的视图,我知道很容易用高度常量=0来折叠它,但我不知道如何使其再次展开,因为该视图的内容是动态的,并且以后可能会添加子ITME 我想要那种行为 您的答案大大简化了一个非常简单的解决方案 您应该首先将zeroHeightConstraint创建为属性 let zeroHeightConstraint: NSLayoutConstraint = dynamicView.heightAnchor.constraint(equalToConst

我有一个问题,我无法创建一个可以折叠其内容(可能是动态高度)的视图,我知道很容易用高度常量=0来折叠它,但我不知道如何使其再次展开,因为该视图的内容是动态的,并且以后可能会添加子ITME

我想要那种行为


您的答案大大简化了一个非常简单的解决方案

您应该首先将
zeroHeightConstraint
创建为属性

let zeroHeightConstraint: NSLayoutConstraint = dynamicView.heightAnchor.constraint(equalToConstant: 0)
如果你愿意,你也可以把它作为故事板的一个出口

现在添加您的按钮操作

@IBAction func toggleCollapisbleView() {
    if animationRunning { return }

    let shouldCollapse = dynamicView.frame.height != 0

    animateView(isCollapse: shouldCollapse,
                buttonText: shouldCollapse ? "Expand" : "Collapse")
}

private func animateView(isCollapse: Bool, buttonText: String) {
    zeroHeightConstraint.isActive = isCollapse

    animationRunning = true

    UIView.animate(withDuration duration: 1, animations: {
        self.view.layoutIfNeeded()
    }, completion: { _ in
        self.animationRunning = false
        self.button.setTitle(buttonText, for: .normal)
    })
}
始终避免在代码中使用
view.tag
。它应该始终被视为“代码气味”。几乎总是有一种更优雅的方式来做你想做的事情

关于底部约束。您应该使用
UIStackView
来布局视图内部的内容。通过这样做,您不再需要迭代
contentView
的子视图,您可以直接访问
UIStackView
。在那里做同样的事情。事实上更好的方法是使用
优先级
小于
1000
的视图创建
bottomConstraint
。e、 g.
999

通过这样做,您根本不必删除或添加该约束。当
zeroHeightConstraint
未激活时,它将在那里工作。当
zeroHeightConstraint
激活时,它将自动覆盖底部约束