1

你好,

我正在尝试在两个不同图像之间为 UIButton 的图像设置动画。

假设我有两个正方形图像,红色,黑色。

当我触摸我的按钮时,我希望 uibutton 的图像以流畅的动画从两个图像中循环。

循环动画必须在用户按下按钮时开始,并在他触摸向上或拖动退出时取消。

这是我现在要做的:

-(void)startAnimation:(UIButton *)obj {
    [UIView animateWithDuration:1 delay:0 options:(UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeat) animations:^{
        [obj setAlpha:0];
        [obj setImage:[UIImage imageNamed:@"animated_on"] forState:UIControlStateNormal];
        [obj setImage:[UIImage imageNamed:@"animated_on"] forState:UIControlStateHighlighted];
        [obj setImage:[UIImage imageNamed:@"animated_on"] forState:UIControlStateDisabled];
        [obj setImage:[UIImage imageNamed:@"animated_on"] forState:UIControlStateSelected];
    } completion:^(BOOL finished) {
        [obj setAlpha:1];
        [obj setImage:nil forState:UIControlStateNormal];
        [obj setImage:nil forState:UIControlStateHighlighted];
        [obj setImage:nil forState:UIControlStateDisabled];
        [obj setImage:nil forState:UIControlStateSelected];        

    }];   
}

-(void)stopAnimation:(UIButton *)obj {
   [obj.layer removeAllAnimations]; 
}

- (void)touchDownAnimation:(id)obj {    
    [self startAnimation:obj];
}

- (void)dragEnterAnimation:(id)obj {
    [self startAnimation:obj];
}
- (void)dragExitAnimation:(id)obj {
    [self stopAnimation:obj];
}

- (void)touchUpInsideAnimation:(id)obj {
    [self stopAnimation:obj];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    CGRect frame = CGRectMake(110, 180, 100, 100);

    UIImageView *animatedButtonBackground = [[UIImageView alloc] initWithFrame:frame];
    [animatedButtonBackground setImage:[UIImage imageNamed:@"animated_off"]];

    [self.view addSubview:animatedButtonBackground];

    UIButton *animatedButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [animatedButton setFrame:frame];

    [animatedButton addTarget:self action:@selector(touchDownAnimation:) forControlEvents:UIControlEventTouchDown];
    [animatedButton addTarget:self action:@selector(dragEnterAnimation:) forControlEvents:UIControlEventTouchDragEnter];
    [animatedButton addTarget:self action:@selector(dragExitAnimation:) forControlEvents:UIControlEventTouchDragExit];    
    [animatedButton addTarget:self action:@selector(touchUpInsideAnimation:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:animatedButton];

}

它有点工作,但在这个过程中涉及一个 UIImageView 看起来像一个坏技巧来做我想做的事......

我正在寻找更清洁的解决方案。

4

1 回答 1

1

想知道你是否可以使用更简单的东西:

button.imageView.animationImages = [NSArray arrayWithObjects:
                                    [UIImage imageNamed:@"image1"],
                                    [UIImage imageNamed:@"image2"],
                                    nil];
button.imageView.animationDuration = 1;
[button.imageView startAnimating];
于 2012-07-31T12:37:32.227 回答