【问题标题】:How to make animation with constrains in swift?如何快速制作带有约束的动画?
【发布时间】:2019-06-16 07:39:02
【问题描述】:

当每个条形图为 UIView 时,我已经编写了一个条形图,并对其高度和超级视图的顶部约束进行了限制。

输入高度值后,应执行持续时间为 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()
}

不幸的是,动画永远不会出现。我的动画有什么问题?

【问题讨论】:

    标签: ios swift animation


    【解决方案1】:

    用这个替换你的动画代码:

    barTopConstraint.constant = newTopConstraint
    heightCons.constant += heightDiff
    
    UIView.animate(withDuration: 10, animations: view.layoutIfNeeded)
    

    当您更新约束时,仅将常量设置为其他值不会更新视图。

    要更新视图,请在要为其更新约束的视图上调用 layoutIfNeeded()

    在这种情况下,我在主视图上调用layoutIfNeeded(),所以每个子视图也会更新。

    将来,如果您想在没有动画的情况下更新约束,请在设置常量后立即调用view.layoutIfNeeded()。如果需要动画,请将layoutIfNeeded 放在UIView.animate 中。

    【讨论】:

    • 更新约束时,仅将常量设置为其他值不会更新视图。要更新视图,请在要为其更新约束的视图上调用 layoutIfNeeded()。在这种情况下,我在主视图上调用layoutIfNeeded(),所以每个子视图也会更新。将来,如果您想在没有动画的情况下更新约束,请在设置常量后立即调用view.layoutIfNeeded()。当你想要一个动画时,把layoutIfNeeded放在UIView.animate里面。
    • 还有,最后一行和UIView.animate(withDuration: 10) { self.view.layoutIfNeeded() }是一样的,只是方式更花哨。
    猜你喜欢
    • 2018-02-10
    • 2014-10-28
    • 1970-01-01
    • 1970-01-01
    • 2015-09-11
    • 2018-06-16
    • 2016-11-29
    • 2013-07-11
    • 2019-06-03
    相关资源
    最近更新 更多