Stopping UIViewAnimation with removeAllAnimations

157 views Asked by At

I have a simple UILabel that starts rotating when you do a long-press on it. I'm achieving this successfully using the following code:

-(IBAction)longPressEffect:(UILongPressGestureRecognizer *)sender {
    if (sender.state == UIGestureRecognizerStateBegan) {

        UIViewAnimationOptions animationOptions = UIViewAnimationCurveLinear | UIViewAnimationOptionRepeat;

        [UIView animateWithDuration:0.4 delay:0.0 options:animationOptions animations:^ {
            labelObject.transform = CGAffineTransformMakeRotation(DegreesToRadians(angle));
        } completion:nil];

        angle = angle + 180;
    }
    else if (sender.state == UIGestureRecognizerStateEnded) {
        ;
    }
}

The user can stop this animation at any point by simply double-clicking on the Label. Here's the code for that:

-(IBAction)doubleTapEffect:(UITapGestureRecognizer *)sender {
    [labelObject.layer removeAllAnimations];
    labelObject.transform = CGAffineTransformMakeRotation(DegreesToRadians(0));

}

The problem is that the next time you do long-press on the Label - it doesn't respond. The rotation animation doesn't start up again. You to have to click on it yet one more time to get it going again.

So the pattern is:
1) Long press - animation starts
2) Double click - animation stops
3) Long Press - nothing happens
4) Long press yet again - animation starts up again.

How do I fix this?

1

There are 1 answers

1
Caroline On

It is animating - it just doesn't look as if it is, because you are adding 180 to the angle all the time.

Assuming that angle is 180 to start with, you animate from 0 to 180 then 180 around to 180 then 180 around to 180. Then angle is + 180, which puts angle at 360, and the initial animation is 360, which is interpreted as 0, so the label animates from 0 to 0.

Change

angle = angle + 180;

to

angle = angle + 30;

and you should see the rotation happening.

This link might help you do a continuous rotation, if that's what you're trying to do:

How can I rotate a UIButton continuously and be able to stop it?