自动版式:如何创建折叠/展开动态视图swift 3/4 [英] Autolayouts : How to create collapse/Expand dynamic view swift 3/4

查看:151
本文介绍了自动版式:如何创建折叠/展开动态视图swift 3/4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我无法创建一个视图来折叠可能是动态高度的内容,我知道用高度 constant = 0 可以很容易地折叠它,但是我可以t找出如何使它再次扩展,因为该视图的内容是动态的,以后可能会添加子主题

I have a problem that I can't create a view that can collapse it's contents that may be dynamic height , i know it's easy to collapse it with height constant = 0 , but i can't figure out how to make it expand again as the content of that view is dynamic and sub-itmes may be added later

我想要这种行为

推荐答案

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

Your answer has massively overcomplicated a very simple solution.

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

You should first create your zeroHeightConstraint as a property.

let zeroHeightConstraint: NSLayoutConstraint = dynamicView.heightAnchor.constraint(equalToConstant: 0)

如果您愿意,也可以将其用作情节提要的出口.

You could do this as an outlet from the storyboard too if you wanted.

现在添加您的按钮操作...

Now add your button action...

@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.应始终将其视为代码异味".几乎总是有一种更加优雅的方式来做您想做的事情.

Always avoid using view.tag in your code. It should always be seen as "code smell". There is almost always a much more elegant way of doing what you are trying to do.

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

Regarding the bottom constraint. You should really be using a UIStackView to layout the contents of the inside of the view here. By doing that you no longer need to iterate the subviews of your contentView you can access the UIStackView directly. And do the same thing there. In fact... a much better way would be to create the bottomConstraint against the view using a priority less than 1000. e.g. 999.

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

By doing that you don't have to remove or add that constraint at all. When the zeroHeightConstraint is not active it will be there and work. When the zeroHeightConstraint is active it will override the bottom constraint automatically.

这篇关于自动版式:如何创建折叠/展开动态视图swift 3/4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆