2011-07-07 12 views
16

Quiero poner un icono en la barra de estado de Mac OS como parte de mi aplicación Cocoa. Lo que hago en este momento es:Cómo agregar un ícono animado a la barra de estado de OS X?

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

pero si quiero el icono para ser animado (3-4 marcos), ¿cómo lo hago?

+2

Bueno, quiero dar la impresión de que la aplicación está procesando datos, esto ocurre con poca frecuencia pero podría ser bueno saberlo. ¿O no debería? – kender

+8

Ese es un uso válido. Diablos, Time Machine lo hace. –

+4

Creo que Dropbox maneja esto bastante bien. Es sutil pero te dice que las cosas se están actualizando. –

Respuesta

27

Deberá llamar repetidamente al -setImage: en su NSStatusItem, pasando una imagen diferente cada vez. La forma más sencilla de hacerlo sería con un NSTimer y una variable de instancia para almacenar el fotograma actual de la animación.

Algo como esto:

/* 

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; 
    } 
} 
+0

¿También es posible colocar NSView o NSImageView en un elemento de la barra de estado? ¿Cómo hacerlo? – zsong

+0

¿tienes que decirle al animTimer que dispare mediante [animTimer fire] o es automático? –

+1

Los métodos '+ scheduledTimerWithTimeInterval: ...' agregarán el temporizador al ciclo de ejecución para usted (ese es el bit 'programado') por lo que no necesita disparar el temporizador usted mismo. –

5

Reescribí solución de Rob para que pueda volver a utilizarlo:

tengo número de cuadros 9 y todo el nombre de imágenes tiene último dígito como número de chasis con el fin que puedo restablecer la imagen cada vez para animar el ícono.

//IntervalAnimator.h 

    #import <Foundation/Foundation.h> 

@protocol IntervalAnimatorDelegate <NSObject> 

- (void)onUpdate; 

@end 


@interface IntervalAnimator : NSObject 
{ 
    NSInteger numberOfFrames; 
    NSInteger currentFrame; 
    __unsafe_unretained id <IntervalAnimatorDelegate> delegate; 
} 

@property(assign) id <IntervalAnimatorDelegate> 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 

Modo de empleo:

  1. Conformarse con el protocolo en su clase StatusMenu

    //create IntervalAnimator object 
    
    animator = [[IntervalAnimator alloc] init]; 
    
    [animator setDelegate:self]; 
    
    [animator setNumberOfFrames:9]; 
    
    [animator startAnimating]; 
    
  2. implementar el método de protocolo

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