CGAffineTransformIdentity not resetting a UIImageView after multiple transforms?

Mark Reid picture Mark Reid · Jul 27, 2011 · Viewed 7.9k times · Source

I have created a simple app with a segmented control at the top. When I click on one of two segments of the control a UIImageView starts to rotate. I have a reset button hooked up to set its transform to CGAffineTransformIdentity.

The problem occurs when the method that does the view rotation animation is called a second time by switching segments back and forth. Hitting reset only removes the most recent animation. I have to switch segments a second time to get the animations to stop with reset entirely.

The following code is called when I select the segment to rotate the UIImageView and obviously called a second time when I click between segments.

// Begin the animation block and set its name
[UIView beginAnimations:@"Rotate Animation" context:nil];

// Set the duration of the animation in seconds (floating point value)
[UIView setAnimationDuration:0.5];

// Set the number of times the animation will repeat (NSIntegerMax setting would repeat indefinately) (floating point value)
[UIView setAnimationRepeatCount:NSIntegerMax];

// Set the animation to auto-reverse (complete the animation in one direction and then do it backwards)
[UIView setAnimationRepeatAutoreverses:YES];

// Animation curve dictates the speed over time of an animation (UIViewAnimationCurveEaseIn, UIViewAnimationCurveEaseOut, UIViewAnimationCurveEaseInOut, UIViewAnimationCurveLinear)
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

// Changes the imageViews transform property to rotate the view using CGAffineTransformRotate
// CGAffineTransformRotate(transformToStartFrom, angleToRotateInRadians)
// Starting transform property can be set to CGAffineTransformIdentity to start from views original transform state
// This can also be done using CGAffineTransformMakeRotation(angleInRadians) to start from the IdentityTransform without implicitly stating so
self.imageView.transform = CGAffineTransformRotate(self.imageView.transform, degreesToRadians(90));

[UIView commitAnimations];

The reset button calls this code -

self.imageView.transform = CGAffineTransformIdentity;

Answer

try this

[UIView animateWithDuration:0.2 animations:^() {
    self.imageView.transform = CGAffineTransformIdentity;
}];