18

What is the best way to animate images of a button?

Say I want to cycle through like 6 frames and have the user still be able to click the button?

Should I animate the images and just have an invisible button on top of it in interface builder?

Is there a way to animate them within defining the UIButton?

Or is it better to animate images and find the users touch point and act on that?

Andriy
  • 2,767
  • 2
  • 21
  • 29
Cherr Skees
  • 1,508
  • 2
  • 21
  • 37

1 Answers1

26

You can do this using the imageView property of UIButton. This will allow the button to behave as it normally would with your images animating on it. Here's an example:

NSMutableArray *imageArray = [NSMutableArray new];

for (int i = 1; i < 4; i ++) {
    [imageArray addObject:[UIImage imageNamed:[NSString stringWithFormat:@"%d.png",i]]];
}

[myButton setImage:[UIImage imageNamed:@"1.png"] forState:UIControlStateNormal];

[myButton.imageView setAnimationImages:[imageArray copy]];
[myButton.imageView setAnimationDuration:0.5];

[myButton.imageView startAnimating];
Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281
  • Ok Good... I didn't know if it would work inside the button like that. Thanks. – Cherr Skees Sep 26 '12 at 20:14
  • How come this work, when myButton.imageView.hidden = YES doesnt ? – bobmoff Feb 19 '14 at 11:19
  • @bobmoff Probably because the imageView still exists when you set it to be hidden. All that changes is the image view's alpha. – Mick MacCallum Feb 19 '14 at 12:27
  • @bobmoff Sorry, I read that wrong. Are you saying that the buttons image view isn't staying hidden when there's an animation? If so, it sounds like the animation might be unhiding the image view on its own internally. – Mick MacCallum Feb 19 '14 at 12:35
  • Forget the animation. Just simply settings the imageView.hidden = YES or imageView.alpha = 0 doesnt work for me. Is it supposed to work ? The image is still showing. The only way to remove the image is to use the setImage:nil forState: method, but I want to be able to animate the alpha from 1 och 0. I simply want to fade the imageView away. – bobmoff Feb 19 '14 at 12:50
  • animated png also option – Jignesh B Feb 19 '14 at 12:51
  • @bobmoff I can't reproduce the problem. – Mick MacCallum Feb 19 '14 at 12:55
  • 1
    Ok, then I have to be doing something else wrong. Thanks for helping me out. :) – bobmoff Feb 19 '14 at 13:19