swift - 为什么 layoutIfNeeded() 允许在更新约束时执行动画?

标签 swift layoutsubviews animatewithduration

UIView 我有两种状态:

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
    }
}

动画只有在我添加额外的行时才有效:

但是当我删除该行时,我的 UIView 会更新但没有任何动画,它会立即发生。

为什么这条线会造成如此大的差异?效果如何?

最佳答案

据我了解,更改约束不会立即更新 View 的布局。它对更改进行排队,并且它们仅在下次系统更新布局时发生。

通过将 layoutIfNeeded 放在动画 block 中,它会强制在动画 block 期间应用 View 更改。否则它们会在动画设置完成后发生。

关于swift - 为什么 layoutIfNeeded() 允许在更新约束时执行动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31361842/

相关文章:

ios - NSCoreDataCoreSpotlightDelegate 索引现有数据

ios - 使用 UIDynamics Swift 制作 UICollectionView 动画

iphone - 在 layoutSubviews 中调用 setNeedsDisplay?

swift - 如何获取 UICollectionView 中每个选定单元格的按钮标题?

IOS/swift : Pass Object in tableview to detail view controller

iphone - 尽管有任何设备旋转,layoutsubviews 只调用一次

iOS自定义UIView设计: init vs layoutSubviews

closures - animateWithDuration:animations:completion: 在 Swift 中

ios - 停止特定的 UIView 动画 block - iOS

ios - 将 UIImageView 从 A 移动到 B