Ios – Animated Images in a UIButton

iosuibuttonuiviewanimationxcode

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?

Best Answer

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