7

我有一个由以下代码创建的 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)];

在这里,当它被点击时,选择器 buttonAction 被调用,我正在像这样通过 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"];
}

它工作得很好,但这并不是我真正想要的。我想要那个,当我的按钮被点击时,按钮会将图像“reload_selected.png”(我为 UIControlStateSelected 设置)作为背景,然后运行动画。动画完成后,按钮将不得不再次返回到它的实际背景(“refresh_icon.png”)。

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

4

2 回答 2

1

可以这样试试吗

[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];
                         }
    ];
于 2013-11-12T07:01:18.763 回答
0

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

编辑:做类似的事情

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

要指定动画,您可能希望transform使用CGAffineTransformRotate.

于 2013-11-12T06:49:14.630 回答