Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Background Image and animate an UIButton when tapped iOS 7 [duplicate]

I have an UIButton created by the following code

    button =  [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:[UIImage imageNamed:@"refresh_icon.png"] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"reload_selected.png"] forState:UIControlStateSelected];
    [button addTarget:self action:@selector(buttonAction:)forControlEvents:UIControlEventTouchUpInside];
    [button setFrame:CGRectMake(0, 0, 20 , 20)];

Here when it's clicked the selector buttonAction is called and I am animating the button by a 360 degree rotation like this

- (void) buttonAction : (id) sender {
    NSLog(@"Reload Button Clicked");
    [self runSpinAnimationOnView:self.button duration:1.0 rotations:1.0 repeat:0];

}

- (void) runSpinAnimationOnView:(UIView*)view duration:(CGFloat)duration rotations:(CGFloat)rotations repeat:(float)repeat;
{
    CABasicAnimation* rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 /* full rotation*/ * rotations * duration ];
    rotationAnimation.duration = duration;
    rotationAnimation.cumulative = YES;
    rotationAnimation.repeatCount = repeat;

    [view.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
}

It's working good but it's not that I actually want. I want that , when my button is clicked then button will take the image "reload_selected.png" (which I set for UIControlStateSelected) as background and then run the animation. When the animation is finished then button will have to return to it's actual background ("refresh_icon.png") again.

Can anyone suggest some change in code that will help me achieve the action I described above ? Thanks in advance for your help.

like image 659
ayon Avatar asked Nov 12 '13 06:11

ayon


1 Answers

Can you try like this,

[UIView animateWithDuration:YOURDURATION
            delay:0
            options:(UIViewAnimationOptionCurveLinear)
            animations:^ {
                          [button setImage:[UIImage imageNamed:@"reload_selected.png"] forState:UIControlStateSelected];
                           button.transform = CGAffineTransformRotate(CGAffineTransformIdentity,M_PI * 2);
                         }
            completion:^(BOOL finished) {
                          [button setImage:[UIImage imageNamed:@"refresh_icon.png"] forState:UIControlStateNormal];
                         }
    ];
like image 75
Vedchi Avatar answered Sep 20 '22 15:09

Vedchi