为什么UIView.animate(withDuration没有效果?

时间:2016-10-24 14:55:52

标签: ios uiview nslayoutconstraint

我尝试使用以下行执行布局更新,但动画是提示,没有延迟。知道为什么吗?使用8.0 Xcode。

UIView.animate(withDuration: 12.0, animations: {

    self.yellowLineLeadingConstraint.isActive = false
    self.yellowLineTrailingConstraint.isActive = false

    self.yellowLineLeadingConstraint = NSLayoutConstraint(item: self.yellowLine, attribute: .leading, relatedBy: .equal, toItem: b, attribute: .leading, multiplier: 1.0, constant: 0)
    self.yellowLineTrailingConstraint = NSLayoutConstraint(item: self.yellowLine, attribute: .trailing, relatedBy: .equal, toItem: b, attribute: .trailing, multiplier: 1.0, constant: 0)

    self.view.addConstraints([self.yellowLineLeadingConstraint, self.yellowLineTrailingConstraint])

    self.yellowLineLeadingConstraint.isActive = true
    self.yellowLineTrailingConstraint.isActive = true
})

2 个答案:

答案 0 :(得分:4)

为布局约束设置动画的正确方法是事先更改它们,并在动画块中调用layoutIfNeeded(这会告诉视图实际更新其布局)。所以你的代码看起来像这样:

self.yellowLineLeadingConstraint.isActive = false
self.yellowLineTrailingConstraint.isActive = false

self.yellowLineLeadingConstraint = NSLayoutConstraint(item: self.yellowLine, attribute: .leading, relatedBy: .equal, toItem: b, attribute: .leading, multiplier: 1.0, constant: 0)
self.yellowLineTrailingConstraint = NSLayoutConstraint(item: self.yellowLine, attribute: .trailing, relatedBy: .equal, toItem: b, attribute: .trailing, multiplier: 1.0, constant: 0)

self.view.addConstraints([self.yellowLineLeadingConstraint, self.yellowLineTrailingConstraint])

self.yellowLineLeadingConstraint.isActive = true
self.yellowLineTrailingConstraint.isActive = true

UIView.animate(withDuration: 12.0, animations: {
    self.view.layoutIfNeeded()
}

答案 1 :(得分:-2)

你不能改变任何可动画的"属性。我看到您正在更新约束属性,但它不是Animatable Properties

中的一个