1
votes

I have two relatively simple animations. One is animating the top constraint of a UIButton so that it slides up. The other is animating the background color on a UIView.

self.buttonAnimationConstant.constant = 0
self.view.layoutIfNeeded() // ensure the constraint is at 0
self.buttonAnimationConstraint.constant = 100
UIView.animateWithDuration(0.25, delay: 0.0) {
    self.view.layoutIfNeeded()
}

and my color animation:

UIView.animateWithDuration(0.25, delay: 0.0) {
    self.colorView.backgroundColor = UIColor.purpleColor()
}

If I try executing them at the same time, then the button will animate up but it cancels the color animation, presumably because of view.layoutIfNeeded. Note that these two animations are in separate places so they can't be joined into one block (one sits at the view controller level, the other embedded inside a custom view but both within the same view controller). How can I animate both a constraint and a view property such that one doesn't cancel the other?

Essentially the issue is how do you go about animating both a constraint and a view that sit in the same view hierarchy?

1
Like @Jelly, I have created a small sample app and cannot reproduce your problem. My sample app has one button. When pressed, the view will animate the button's top constraint to move the button and will change the background color of the view. The background color animation is registered first, then view.layoutIfNeeded() is called, then the animation to move the button is registered. - keithbhunter
Then it's probably some side-effect I'm not seeing. Thanks all! - barndog

1 Answers

2
votes

Animation blocks do not cancel each other. The issue here is this line:

self.view.layoutIfNeeded() // ensure the constraint is at 0

Calling layoutIfNeeded outside an animation block will cancel your animations (because they set a new value for the values you animate) and there is not much you can do to prevent that. What you could do is making sure that no layoutIfNeeded is called outside an animation block while performing an animation. Of course this does not happen if the views are not in the same view hierarchy.