为什么layoutIfNeeded()允许在更新约束时执行动画?
问题描述:
我有UIView
两种状态:为什么layoutIfNeeded()允许在更新约束时执行动画?
我使用@IBaction
为button
它们之间的动画:
@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
更新,但没有任何动画,它立即发生。
为什么这条线有这样的区别?它是如何工作的?
答
据我所知,更改约束并不会立即更新视图的布局。它将更改排队,并且只有在系统下次更新布局时才会发生。
通过将layoutIfNeeded放入您的动画块中,它强制在动画块中应用视图更改。否则,他们会在动画创建完成后稍后进行。