在点击iOS 7时更改背景图像并为UIButton设置动画

ayo*_*yon 7 core-animation objective-c uibutton ios

我有一个由以下代码创建的UIButton

    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)];
Run Code Online (Sandbox Code Playgroud)

在这里点击选择器按钮动作被调用,我通过这样的360度旋转动画按钮

- (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"];
}
Run Code Online (Sandbox Code Playgroud)

它运作良好,但并不是我真正想要的.我想要的是,当我点击我的按钮时,按钮会将图像"reload_selected.png"(我为UIControlStateSelected设置)作为背景,然后运行动画.动画完成后,按钮必须再次返回其实际背景("refresh_icon.png").

任何人都可以建议一些代码更改,以帮助我实现上述的操作吗?在此先感谢您的帮助.

Ros*_*han 0

animateWithDuration:animations:completion:您可以使用的方法,而不是使用 Core Animation UIView。此方法允许您指定一个完成块,您可以使用它在动画完成后重置图像。

编辑:做类似的事情

[view animateWithDuration:duration animations:^{
    //Do your animations here
} completion: ^(BOOL finished){
    if(finished) {
        //reset the image
    }
}];
Run Code Online (Sandbox Code Playgroud)

要指定动画,您可能需要transform使用动画视图的属性CGAffineTransformRotate