views:

522

answers:

3

Is there any way to set an animated image like the Apple spinning gear to an UIBarButtonItem?

I have tried this line of code but the animated gif image wont play:

myButton.image = [UIImage imageNamed:@"spinningGear.gif"];

Solution found here: How to use a custom UIBarButtonItem to display a UIActivityIndicatorView

+2  A: 

Try creating a UIActivityIndicatorView and assigning it to your button with -[UIBarButtonItem initWithCustomView:].

Ole Begemann
That doesn't work. I don't know where you tried it - doesn't work in iOS 3, and doesn't seem to work in iOS 4 either
Adam
A: 

I don't think that's possible with UIBarButtonItem.

You might want to use customView for that (the property or initWithCustomView) and use UIImageView as that view. That still won't animate gif's "out of the box" (just checked).

If you do so you have two options:

  • use animatedImages from UIImageView class and use separate images for every frame (writing out of head - code might have some errors):

NSMutableArray * imgs = [NSMutableArray array];
for(int i = 0; i < NUMBER_OF_FRAMES; i++) {
    [imgs addObject: [UIImage imageNamed: [NSString stingWithFormat: @"anim%d.png", i]]];
}
UIImageView * imgview = [[UIImageView alloc] init];
imgview.animatedImages = imgs;
[imgview startAnimating];

shw
A: 

I found that this line was incorrect:

[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];

...the actual size of the default Refresh button from Apple is a little different. If you have other items doing auto-layout on that toolbar, you need to get the size right.

Unfortunately, Apple provides no API for finding out the size. By trial and error, it seems this is correct:

[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 28, 28)];
Adam