Thursday, April 21, 2011

iPhone SDK: set animated loading (gear) image to UIBarButtonItem

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

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

    Adam : 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
  • 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];

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


Post a Comment