21

Before Auto-layout, I've been animating a background's height in a project by setting the frame over 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 UIView dimensions with CGRect.

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

2 Answers 2

51

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

func AnimateBackgroundHeight() {
    UIView.animateWithDuration(0.5, animations: {
         self.heightCon.constant = 600 // heightCon is the IBOutlet to the constraint
         self.view.layoutIfNeeded()    
    })
}
1
  • how to get the height during animation of a view? Apr 6, 2018 at 9:37
7

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.animateWithDuration block. 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.

1
  • 4
    Spent 7 hours trying to figure out why my layout was breaking when animating. After seeing you posts I realized I was calling layoutIfNeeded on a subview not the superview. Thanks!!
    – JoakimE
    Jan 7, 2017 at 19:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.