How to add animated icon to OS X status bar?

前端 未结 3 1095
你的背包
你的背包 2021-01-30 02:34

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 =          


        
3条回答
  •  迷失自我
    2021-01-30 03:17

    I re-wrote Rob's solution so that I can reuse it:

    I have number of frames 9 and all the images name has last digit as frame number so that I can reset the image each time to animate the icon.

    //IntervalAnimator.h
    
        #import 
    
    @protocol IntervalAnimatorDelegate 
    
    - (void)onUpdate;
    
    @end
    
    
    @interface IntervalAnimator : NSObject
    {
        NSInteger numberOfFrames;
        NSInteger currentFrame;
        __unsafe_unretained id  delegate;
    }
    
    @property(assign) id  delegate;
    @property (nonatomic) NSInteger numberOfFrames;
    @property (nonatomic) NSInteger currentFrame;
    
    - (void)startAnimating;
    - (void)stopAnimating;
    @end
    
    #import "IntervalAnimator.h"
    
    @interface IntervalAnimator()
    {
        NSTimer* animTimer;
    }
    
    @end
    
    @implementation IntervalAnimator
    @synthesize numberOfFrames;
    @synthesize delegate;
    @synthesize currentFrame;
    
    - (void)startAnimating
    {
        currentFrame = -1;
        animTimer = [NSTimer scheduledTimerWithTimeInterval:0.50 target:delegate selector:@selector(onUpdate) userInfo:nil repeats:YES];
    }
    
    - (void)stopAnimating
    {
        [animTimer invalidate];
    }
    
    @end
    

    How to use:

    1. Conform to protocol in your StatusMenu class

      //create IntervalAnimator object
      
      animator = [[IntervalAnimator alloc] init];
      
      [animator setDelegate:self];
      
      [animator setNumberOfFrames:9];
      
      [animator startAnimating];
      
    2. Implement protocol method

      -(void)onUpdate    {
      
          [animator setCurrentFrame:([animator currentFrame] + 1)%[animator numberOfFrames]];
      
          NSImage* image = [NSImage imageNamed:[NSString stringWithFormat:@"icon%ld", (long)[animator currentFrame]]];
      
          [statusItem setImage:image];
      
      }
      

提交回复
热议问题