我设置了一个动画,以便在另一个开关/标签打开时隐藏它。同时刚打开的开关向上移动。这很好用简单的解释here。
但是,当我尝试在关闭后将开关/标签向下移动时,它不会让步。另一个开关重新出现,但顶部约束更改不会触发。
我是相对较新的做这种类型的设置和所有编程动画,并花了一个小时后,我很难过。是因为我正在制作相对于另一个的顶级约束吗?如果它第一次工作,这有什么关系?即使隐藏开关的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()
})
}
这里的问题是你没有修改约束,但实际上是为每个动画创建新的约束。你要做的只是创建一次约束(你可以在代码或Interface Builder中拖放)。然后,您可以只更改动画块中现有约束的.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()
})
}