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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29248203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 05:20:06  来源:igfitidea点击:

Animate UIView height when using auto layout with swift

iosswiftuiviewxcode6

提问by Poyi

Before Auto-layout, I've been animating a background's height in a project by setting the frame over animateWithDuration.

在自动布局之前,我一直在通过将框架设置为 来为项目中的背景高度设置动画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)    
    })
}

After I converted my project to auto layout, I noticed that the animation occurs but the background height snaps back to the original size/style (interface builder setting) after. I read that when Auto-layout is turned on, the constraints will overwrite setting the UIViewdimensions with CGRect.

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

Therefore I'm wondering how to go about achieving the same height change animation effect with Auto-layout ON.

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

回答by rdelmar

Give your backgroundView a height constraint, and make an IBOutlet to it. In code, modify the constraint's constant value.

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

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

回答by Sethmr

Also for those of you who find this post trying to figure out why a transition changing a view's size will be blocky or unclean you just need to find the view in charge and call self.view.layoutIfNeeded()inside of the UIView.animateWithDurationblock. I was banging my head against the wall trying different things with constraints and making frames until realizing that self.view.layoutIfNeeded()will handle making the transition smooth as long as you are placing it in the right location.

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