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

Poy*_*oyi 20 uiview ios swift xcode6

在自动布局之前,我通过设置框架来设置项目中背景的高度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)    
    })
}
Run Code Online (Sandbox Code Playgroud)

在我将项目转换为自动布局后,我注意到动画发生但背景高度在之后快速恢复到原始大小/样式(界面构建器设置).我读到,当打开自动布局时,约束将覆盖设置UIView尺寸CGRect.

因此,我想知道如何在Auto-layout ON的情况下实现相同的高度变化动画效果.

rde*_*mar 47

为backgroundView提供一个高度约束,并为其创建一个IBOutlet.在代码中,修改约束的常量值.

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


Set*_*hmr 6

同样对于那些发现这篇文章的人试图弄清楚为什么改变视图大小的转换将是块状或不干净的你只需要找到负责的视图并调用块self.view.layoutIfNeeded()内部UIView.animateWithDuration.我正在用头撞击墙壁,尝试不同的约束和制作框架,直到意识到self.view.layoutIfNeeded()只要你把它放在正确的位置就能使过渡变得平滑.

  • 花了7个小时试图弄清楚为什么我的布局在动画时破坏了.看到你的帖子后,我意识到我在子视图而不是superview上调用layoutIfNeeded.谢谢!! (2认同)