2015-07-11 27 views
2

我有UIView两种状态:为什么layoutIfNeeded()允许在更新约束时执行动画?

enter image description here enter image description here

我使用@IBactionbutton它们之间的动画:

@IBAction func tapped(sender: UIButton) { 
    flag = !flag 
    UIView.animateWithDuration(1.0) { 
     if self.flag { 
      NSLayoutConstraint.activateConstraints([self.myConstraint]) 
     } else { 
      NSLayoutConstraint.deactivateConstraints([self.myConstraint]) 
     } 
     self.view.layoutIfNeeded() //additional line 
    } 
} 

动画工作只有当我添加额外的行

但是当我r emove那条线,然后我的UIView更新,但没有任何动画,它立即发生。

为什么这条线有这样的区别?它是如何工作的?

回答

2

据我所知,更改约束并不会立即更新视图的布局。它将更改排队,并且只有在系统下次更新布局时才会发生。

通过将layoutIfNeeded放入您的动画块中,它强制在动画块中应用视图更改。否则,他们会在动画创建完成后稍后进行。