我编写了一个条形图,当每个条形图都是 UIView
时,它的高度和顶部约束都限制在 super View 中。
输入高度值后,应执行时长为 10 秒的动画。
但是,动画不会出现。
我首先计算栏的新高度:
let portion = Float(self.currentValue!) / Float(self.maxValue!) // portion of max height of the bar
let newTopConstraint = Float(maxTopConstraint) * portion // the new distance from the top of the superview
var heightDiff = newTopConstraint - Float(self.barTopConstraint.constant)
heightDiff = abs(heightDiff)
现在我得到了栏的新高度,我想将它动画到那个位置:
UIView.animate(withDuration: 10) {
self.barTopConstraint.constant = newTopConstraint
self.heightCons.constant += heightDiff
self.barView.setNeedsLayout()
}
不幸的是,动画永远不会发生。我的动画有什么问题?
最佳答案
用这个替换你的动画代码:
barTopConstraint.constant = newTopConstraint
heightCons.constant += heightDiff
UIView.animate(withDuration: 10, animations: view.layoutIfNeeded)
更新约束时,仅将常量设置为其他内容不会更新 View 。
要更新 View ,请在要为其更新约束的 View 上调用 layoutIfNeeded()
。
在这种情况下,我在主视图上调用 layoutIfNeeded()
,因此每个 subview 也会更新。
将来,如果您想更新没有动画的约束,请在设置常量后立即调用 view.layoutIfNeeded()
。当您需要动画时,将 layoutIfNeeded
放在 UIView.animate
中。
关于ios - 如何快速制作带约束的动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56617025/