更改背景图像并在iOS 7中轻击UIButton时进行动画处理

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")。

有人可以建议一些代码更改来帮助我实现上述操作吗?感谢您提前的帮助。

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];
                         }
    ];

我已经在名为buttonAction的选择器中尝试过了,但不幸的是它没有动画效果。这个按钮已经被设置为UIBarbuttonItem中的自定义视图。 - ayon
所以你想要旋转一个UIBarButtonItem?是这样吗? - Vedchi
是的,我正在尝试做到这一点。 - ayon

0

除了使用核心动画,您还可以使用UIViewanimateWithDuration:animations:completion:方法。此方法允许您指定一个完成块,您可以在动画完成后使用它来重置图像。

编辑: 进行如下操作

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

为了指定动画效果,您可以使用CGAffineTransformRotate来对视图的transform属性进行动画处理。


谢谢你的回答。你能推荐一些示例代码吗? - ayon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接