OK, just built this to check if it would work.
In Swift (because I'm learning) I've done this...
import UIKit
class ViewController: UIViewController {
@IBOutlet var rotatingView : UIView
var rotating = false
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func start(sender : AnyObject) {
rotating = true
rotateOnce()
}
func rotateOnce() {
UIView.animateWithDuration(1.0,
delay: 0.0,
options: .CurveLinear,
animations: {self.rotatingView.transform = CGAffineTransformRotate(self.rotatingView.transform, 3.1415926)},
completion: {finished in self.rotateAgain()})
}
func rotateAgain() {
UIView.animateWithDuration(1.0,
delay: 0.0,
options: .CurveLinear,
animations: {self.rotatingView.transform = CGAffineTransformRotate(self.rotatingView.transform, 3.1415926)},
completion: {finished in if self.rotating { self.rotateOnce() }})
}
@IBAction func stop(sender : AnyObject) {
rotating = false
}
}
Essentially, each single rotation is one animation. Then in the completion block I inspect a boolean rotating
. If rotating == true
then I run the rotation again. and again. and again.
When rotating == false
then I just don't run the animation again from the completion block.
This ensures that the last animation gets to its end before actually stopping the animation.
Objective-C version
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIView *rotatingView;
@property (nonatomic, assign) BOOL rotating;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)startRotating:(id)sender {
self.rotating = YES;
[self firstRotation];
}
- (IBAction)stopRotating:(id)sender {
self.rotating = NO;
}
- (void)firstRotation
{
[UIView animateWithDuration:1.0
delay:0.0
options:UIViewAnimationOptionCurveLinear
animations:^{
self.rotatingView.transform = CGAffineTransformRotate(self.rotatingView.transform, M_PI);
}
completion:^(BOOL finished) {
[self secondRotation];
}];
}
- (void)secondRotation
{
[UIView animateWithDuration:1.0
delay:0.0
options:UIViewAnimationOptionCurveLinear
animations:^{
self.rotatingView.transform = CGAffineTransformRotate(self.rotatingView.transform, M_PI);
}
completion:^(BOOL finished) {
if (self.rotating) {
[self firstRotation];
}
}];
}
@end