swift 使用自动布局时动画 UIView 高度

Animate UIView height when using auto layout with swift

在自动布局之前,我一直在通过在 animateWithDuration 上设置框架来为项目中的背景高度设置动画。

func setUpBackground() {
    self.backgroundView.frame = CGRect(x: 0, y: 0, width: 320, height: 10)
    self.backgroundView.backgroundColor = UIColorFromRGB(0x2d2d2d).CGColor
}

func AnimateBackgroundHeight() {
    UIView.animateWithDuration(0.5, animations: {
        self.backgroundView.frame = CGRect(x: 0, y: 0, width: 320, height: 600)    
    })
}

在我将我的项目转换为自动布局后,我注意到出现了动画,但背景高度在之后迅速恢复到原来的 size/style(界面生成器设置)。我读到当自动布局打开时,约束将用 CGRect.

覆盖设置 UIView 尺寸

所以我想知道如何在启用自动布局的情况下实现相同的高度变化动画效果。

给你的 backgroundView 一个高度约束,并为它创建一个 IBOutlet。在代码中,修改约束的常量值。

func AnimateBackgroundHeight() {
    UIView.animateWithDuration(0.5, animations: {
         self.heightCon.constant = 600 // heightCon is the IBOutlet to the constraint
         self.view.layoutIfNeeded()    
    })
}

同样对于那些发现这个 post 试图弄清楚为什么改变视图大小的过渡会是块状或不干净的人,您只需要找到负责的视图并调用 self.view.layoutIfNeeded()UIView.animateWithDuration 块内。我一直在用头撞墙尝试不同的东西并制作框架,直到意识到 self.view.layoutIfNeeded() 只要将它放在正确的位置就可以使过渡平滑。