Question

I have an UIImageView that runs across the screen when a button is pressed and held. When the button is pressed is changes the UIImage of the UIImageView and when the button is let go I change it to its original UIImage. When ever the image changes back it snaps back to the location that the image started.

This Timer is called when the button is pressed:

//This is the image that changes when the button is pressed.
imView.image = image2;
runTimer = [NSTimer scheduledTimerWithTimeInterval:0.04
                                            target:self
                                          selector:@selector(perform)
                                          userInfo:nil
                                           repeats:YES];

This is called When the button stops being held:

- (IBAction)stopPerform:(id)sender{
   [runTimer invalidate];

   //THIS IS WHAT SNAPS THE ANIMATION BACK:
   //Without this the animation does not snap back
   imView.image = image1;
}

- (void)performRight{

 CGPoint point0 = imView.layer.position;
 CGPoint point1 = { point0.x + 4, point0.y };

 CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"position.x"];
 anim.fromValue    = @(point0.x);
 anim.toValue  = @(point1.x);
 anim.duration   = 0.2f;
 anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];

 // First we update the model layer's property.
 imView.layer.position = point1;

 // Now we attach the animation.
 [imView.layer  addAnimation:anim forKey:@"position.x"];
}

Do I need to add the change in images to the animation? If so how? Im really confused.

Was it helpful?

Solution

Core Animation uses different sets of properties to represent an object:

From Core Animation Programming Guide:


model layer tree (or simply “layer tree”) are the ones your app interacts with the most. The objects in this tree are the model objects that store the target values for any animations. Whenever you change the property of a layer, you use one of these objects.

presentation tree contain the in-flight values for any running animations. Whereas the layer tree objects contain the target values for an animation, the objects in the presentation tree reflect the current values as they appear onscreen. You should never modify the objects in this tree. Instead, you use these objects to read current animation values, perhaps to create a new animation starting at those values.


So when you animate the properties you change the presentation layer, but once the animation is finished the object reverts back to its model property values.

What you need to do to fix this is use the [CAAnimation animationDidStop:finished:] delegate method to set the final property value and anything else you would like to do. I think you could use this to dump that horrible NSTimer code you are using and one small part of the world will be that much better.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top