Autolayouts:如何创建折叠/展开动态视图swift 3/4

Sh_*_*han -8 ios autolayout swift swift3

我有一个问题,我不能创建一个可以折叠它的内容,可能是动态高度,我知道它很容易崩溃高度常数= 0,但我无法弄清楚如何让它再次扩展为该视图的内容是动态的,子视图可能会在以后添加

我想要那种行为

在此输入图像描述

Fog*_*ter 14

您的答案大大过于复杂,这是一个非常简单的解决方案.

您应该首先创建zeroHeightConstraint一个属性.

let zeroHeightConstraint: NSLayoutConstraint = dynamicView.heightAnchor.constraint(equalToConstant: 0)
Run Code Online (Sandbox Code Playgroud)

如果你愿意,你也可以将它作为故事板的出口.

现在添加你的按钮动作......

@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)
    })
}
Run Code Online (Sandbox Code Playgroud)

始终避免view.tag在代码中使用.应始终将其视为"代码味".做你想做的事情几乎总是有一种更优雅的方式.

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

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