I want to put an icon in Mac OS status bar as part of my cocoa application. What I do right now is:
NSStatusBar *bar = [NSStatusBar systemStatusBar];
sbItem = [bar statusItemWithLength:NSVariableStatusItemLength];
[sbItem retain];
[sbItem setImage:[NSImage imageNamed:@"Taski_bar_icon.png"]];
[sbItem setHighlightMode:YES];
[sbItem setAction:@selector(stopStart)];
but if I want the icon to be animated (3-4 frames), how do I do it?
You'll need to repeatedly call -setImage:
on your NSStatusItem
, passing in a different image each time. The easiest way to do this would be with an NSTimer
and an instance variable to store the current frame of the animation.
Something like this:
/*
assume these instance variables are defined:
NSInteger currentFrame;
NSTimer* animTimer;
*/
- (void)startAnimating
{
currentFrame = 0;
animTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/30.0 target:self selector:@selector(updateImage:) userInfo:nil repeats:YES];
}
- (void)stopAnimating
{
[animTimer invalidate];
}
- (void)updateImage:(NSTimer*)timer
{
//get the image for the current frame
NSImage* image = [NSImage imageNamed:[NSString stringWithFormat:@"image%d",currentFrame]];
[statusBarItem setImage:image];
currentFrame++;
if (currentFrame % 4 == 0) {
currentFrame = 0;
}
}