下面是我用来移动和收缩标签的代码。它工作得很好,直到我把它变成一个扩展。现在属性有了动画,但约束没有了。我已经多次看到同样的问题被问过,但解决方案似乎都很简单,而且没有一个有效。我尝试过将约束常量以及 layoutIfNeeded
() 移动到动画上方、alpha 设置下方、上方和下方......但没有成功。
extension UIView {
func moveLabel(lc: NSLayoutConstraint, hc: NSLayoutConstraint) {
lc.constant = -1
hc.constant = 24
UIView.animate(withDuration: 0.5, delay: 0, options: [.curveEaseInOut], animations: {
self.transform = CGAffineTransform(scaleX: 0.7, y: 0.7)
self.alpha = 0.5
self.layoutIfNeeded()
}, completion: nil)
}
}
最佳答案
因为你说“我用来移动和缩小标签”,我怀疑你的问题是由于你在标签本身上调用 self.layoutIfNeeded()
,这将更新当前 View 范围内的约束,但移动 View 需要布局 super View 。作为测试,您还可以在动画 block 中包含 self.superview?.layoutIfNeeded()
,但如果您想确定,请将标签的 super View 传递给该函数并调用 layoutIfNeeded ()
对此。
extension UIView {
func moveLabel(lc: NSLayoutConstraint, hc: NSLayoutConstraint, superView: UIView) {
lc.constant = -1
hc.constant = 24
UIView.animate(withDuration: 0.5, delay: 0, options: [.curveEaseInOut], animations: {
self.transform = CGAffineTransform(scaleX: 0.7, y: 0.7)
self.alpha = 0.5
self.layoutIfNeeded()
superView.layoutIfNeeded()
}, completion: nil)
}
}
附:在您的代码中,您实际上并没有对约束进行动画处理,这是您的意图吗?
关于扩展中的 Swift Animate 约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54702991/