Hi,
i'm trying to animate the image of a UIButton between two different image.
Let's say i have two square images, on RED, on BLACK.
When i touch my Button, i want the image of the uibutton to loop from both images, in a smooth animation.
the loop animation must start whenever the user touch down the button and canceled when he touch Up inside or drag exit.
Here is what i do now :
-(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];
}
it's kinda works, but involving an UIImageView in the process looks like a bad trick to do what i want...
i'm looking for a cleaner solution.