相对于另一个的动画约束



我设置了一个动画,以隐藏一个开关/标签时,当另一个打开另一个开关时。同时,刚打开的开关向上移动。这与这里的简单解释非常有用。

但是,当我尝试将开关/标签移回后,将其关闭时,它不会放弃。另一个开关重新出现,但是顶部的约束更改不会发射。

我对进行此类设置并以编程方式进行动画动画相对较新,并且花了一个小时在我身上。这是因为我正在为另一个限制动画吗?如果第一次工作起作用,这有什么关系?即使隐藏开关的alpha设置为零,它的框架仍然存在,对吗?还是我在做简单的事情?

// Works Perfectly!
func hideVeg() {
    self.view.layoutIfNeeded()
    UIView.animate(withDuration: 1, delay: 0, options: [.curveEaseIn], animations: {
        self.vegetarianSwitch.alpha = 0
        self.vegetarianLabel.alpha = 0
        self.veganSwitch.topAnchor.constraint(equalTo: self.vegetarianSwitch.bottomAnchor, constant: -30).isActive = true
        self.view.layoutIfNeeded()
    })
}
// Showing the label and switch works, but the topAnchor constraint never changes!
func showVeg() {
    self.view.layoutIfNeeded()
    UIView.animate(withDuration: 1, delay: 0, options: [.curveEaseIn], animations: {
        self.vegetarianSwitch.alpha = 1
        self.vegetarianLabel.alpha = 1
        // This is the constraint that doesn't change.
        // This is exactly what it was set to before the other hideVeg() runs.
        self.veganSwitch.topAnchor.constraint(equalTo: self.vegetarianSwitch.bottomAnchor, constant: 40).isActive = true
        self.view.layoutIfNeeded()
    })
}

这里的问题是您不是在修改约束,而是在每个动画中实际创建新约束。相反,您要做的就是创建一次约束(您可以在代码或接口构建器中进行操作以及拖动和插座)。然后,您只需更改动画块中现有约束的.constant字段。

需要通过动画更改常数,而不是创建全新的约束。旧约束仍然存在引起问题。

var veganTopConstraint = NSLayoutConstraint()
// Top Constraint set up this way so it can be animated later.
veganTopConstraint = veganSwitch.topAnchor.constraint(equalTo: vegetarianSwitch.bottomAnchor, constant: 40)
veganTopConstraint.isActive = true

func hideVeg() {
    UIView.animate(withDuration: 1, delay: 0, options: [.curveEaseIn], animations: {
        self.vegetarianSwitch.alpha = 0
        self.vegetarianLabel.alpha = 0
        self.veganTopConstraint.constant = -30
        self.view.layoutIfNeeded()
    })
}
func showVeg() {
    self.view.layoutIfNeeded()
    UIView.animate(withDuration: 1, delay: 0, options: [.curveEaseIn], animations: {
        self.vegetarianSwitch.alpha = 1
        self.vegetarianLabel.alpha = 1
        self.veganTopConstraint.constant = 40
        self.view.layoutIfNeeded()
    })
}

最新更新