ios - 如何快速制作带约束的动画?

标签 ios swift animation

我编写了一个条形图,当每个条形图都是 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/

相关文章:

ios - UITextField 文本更改事件

ios - CIDetector,检测到的人脸图像没有显示?

java - 如何使用 AnimatorSet 播放多个动画?

Android动画速度太慢

java - 动画在特定时间开始

ios - 如何在 audioPlayerDidFinishPlaying 方法中使用多个 play()

iphone - 以编程方式识别 iphone 设备

ios - 如何使用 touchesBegan 和 touchesEnded 检测点击手势

xcode - 使用 Swift 在 Storyboard之间切换

ios - 在 UICollectionView 中将单元格居中(水平)对齐