我设置了一个动画,以在打开另一个开关/标签时隐藏一个开关/标签。同时刚刚打开的开关向上移动。通过简单的解释,这非常有效 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 中进行,然后拖动并导出)。然后,您只需更改动画 block 中现有约束的 .constant
字段即可。
关于ios - 动画约束相对于另一个约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55127297/