A Simple Way to Animate a UIBarButtonItem

My first pass solution to animate a UIBarButtonItem was to initialize it's custom view with a UIImageView. The UIImageView can then be set up for animation with multiple images. Calling startAnimaiton/stopAnimation on the UIImaveView will then animate. This is great for animating buttons in tool and tab bars.

One problem is that the when initializing the UIImageView into the UIBarButtonItem, the UIBarButtonItem does not respond to touch events. Yuk.

A simple solution is to initialize the UIBarButtonItem custom view with a UIButton, then touch events for the UIBarButtonItem item are handle correctly.

But the UIButton does not have a way to use a UIImageView only UIImages. We want to use the UIImageView for its simple animation.

The solution is to add the UIImageView as a subview of the UIButton.

Here is the code.

NSArray *images = [NSArray arrayWithObjects:

        [UIImage imageNamed:@"image0.png"],

        [UIImage imageNamed:@"image1.png"],

        nil];

imageView = [[UIImageView allocinitWithImage:[UIImage  imageNamed:@"image0.png"]];

imageView.animationImages = images;


UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

button.bounds = self.imageView.bounds;

[button addSubview:self.imageView];

[button addTarget:self action:@selector(buttonTouched:) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *barButton = [[[UIBarButtonItem alloc] initWithCustomView: button] autorelease];



Some things to notice:

The UIButton is of zero area as it does not have its bounds set upon initialization, thus the bounds are initialized with the bounds of the UIImageView (which has its bounds initialized from the image).


The UIButton handles the action/target for the touch event. The UIBarButtonItem's action/target are not set.



To animate:

    [imageView startAnimating];


Have fun,
Sean

smiceli@smiceli.com