I am animating a UIImageView up and down when the view loads by calling the method animateSettings which does the following:
- (void)animateSettings {
NSLog(@"Animate Settings");
[UIView animateWithDuration:1.0f
delay:0.0f
options:(UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeat | UIViewKeyframeAnimationOptionAllowUserInteraction | UIViewAnimationOptionBeginFromCurrentState)
animations:^{
self.waterImageView.center = CGPointMake(self.view.bounds.size.width/2, self.view.bounds.size.height/2-75);
}
completion:nil];
}
The problem is that when I exit the app and return, the animation freezes. I understand why that is, but I can't seem to figure out how to resume it.
I've set NSNotifications
in the viewDidLoad method to notify me when the view becomes active or it enters the background. Doing the following I call the animateSettings
method or removeAnimation
method.
[[NSNotificationCenter defaultCenter]addObserver:self
selector:@selector(animateSettings)
name:UIApplicationDidBecomeActiveNotification
object:nil];
[[NSNotificationCenter defaultCenter]addObserver:self
selector:@selector(removeAnimation)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
Here's my removeAnimation method
- (void)removeAnimation {
NSLog(@"Remove Animation");
[self.waterImageView.layer removeAllAnimations];
}
Problem: Even though the method are being called correctly (NSLogging works) the animation is still frozen.
The first time you start animating (let's call it 1) animation code says:
self.waterImageView.center =
CGPointMake(self.view.bounds.size.width/2, self.view.bounds.size.height/2-75);
Now let's say you go into the background and return. Your animation code is called again (let's call this 2):
self.waterImageView.center =
CGPointMake(self.view.bounds.size.width/2, self.view.bounds.size.height/2-75);
Okay, but where is self.waterImageView
right now, during 2? It is already at CGPointMake(self.view.bounds.size.width/2, self.view.bounds.size.height/2-75)
- because that is where you put it during 1!
Therefore nothing happens, because there is no animation if there is no change in the value of the animatable property.
Knowing this, the solution is obvious. When you go into the background, or if the animation is stopped for any reason, put the view back where it was to start with. Now when you start the animation again, the view has somewhere to animate to.