Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to rotate a UIButton continuously as a means of indicating that an app is recording something. Is this a good idea. I also want to be able to stop this continuous rotation.

How would I use animation to do this?

like image 954
Mario Avatar asked Sep 07 '11 05:09

Mario


2 Answers

Try below code that will help you because I run that code successfully.

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:@"Show View" forState:UIControlStateNormal];
    button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
    [self.view addSubview:button];

    CABasicAnimation *halfTurn;
    halfTurn = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    halfTurn.fromValue = [NSNumber numberWithFloat:0];
    halfTurn.toValue = [NSNumber numberWithFloat:((360*M_PI)/180)];
    halfTurn.duration = 0.5;
    halfTurn.repeatCount = HUGE_VALF;
    [[button layer] addAnimation:halfTurn forKey:@"180"];
like image 22
Nikunj Jadav Avatar answered Oct 04 '22 20:10

Nikunj Jadav


Use the UIView animation method:

animateWithDuration:delay:options:animations:completion:

and use the option UIViewAnimationOptionRepeat

For example for a UIButton * outlet named button:

- (void)viewDidLoad
{
    [super viewDidLoad];
    [UIView animateWithDuration:2.0 delay:0.0 options:UIViewAnimationOptionRepeat | UIViewAnimationOptionCurveLinear animations:^{
        CGAffineTransform transform = CGAffineTransformMakeRotation(M_PI);
        self.button.transform = transform;
    } completion:NULL];
}

Since it's going round and round, I just rotate it by pi radians rather than 2pi. you could use any angle you want.

Edit

To stop the animation, just create another animation of a short duration beginning from the current state, e.g.

- (void)stopRotating {
    [UIView animateWithDuration:0.1 delay:0.0 options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveLinear animations:^{
        CGAffineTransform transform = CGAffineTransformMakeRotation(M_PI * 0.05);
        self.button.transform = transform;
    } completion:NULL];
}

This provides a very short animation which overrides the current animation. Note that the angle of the transform is multiplied by 0.05 which is the ratio of 0.1/2.0 which means that the rotational speed for this little segment is the same as the continuous rotational speed.

like image 172
Abizern Avatar answered Oct 04 '22 20:10

Abizern