cocoa应用程序中NSStatusItem的使用

mac上的应用程序除了左上方会有菜单之外,在屏幕的右上方也会有一个图标样的菜单,这个类似于windows上右下角的system tray。

本文讲述如何给自己的应用程序添加一个system tray(在mac上应该叫状态栏吧,status item)

1. 创建cocoa的application,名字为MyStatusItem,其他默认选项。

2. 导入两个文件,名为StatusItemController,如下图所示:

3. 准备好2个png文件,icon.png以及icon@2x.png,选中拖拽到Project上,然后会弹出窗口要求copy并导入这两个resource文件,都选默认。

4. 添加一个object知道MainMenu.xib中,并选中Class为刚刚导入的StatusItemController.

5. 跟第4步一样的方法,拖入一个Menu项,然后重命名各个menu item的名字。

    我就写了2个,一个打开主界面一个关闭程序

6. 修改文件如下:

//
//  AppDelegate.h
//  MySatusItem
//
//  Created by user on 12/3/14.
//  Copyright (c) 2014 user. All rights reserved.
//

#import <Cocoa/Cocoa.h>
#import "StatusItemController.h"

@interface AppDelegate : NSObject <NSApplicationDelegate,StatusItemDelegate>

@property (assign) IBOutlet NSWindow *window;

@end
//
//  AppDelegate.m
//  MySatusItem
//
//  Created by user on 12/3/14.
//  Copyright (c) 2014 user. All rights reserved.
//

#import "AppDelegate.h"

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    // Insert code here to initialize your application
}

-(IBAction)openMainConsole:(id)sender
{
    NSLog(@"open Main console from status item");
    NSWindow *window = [self window];
    [window makeKeyAndOrderFront:nil];
}
@end
//
//  StatusItemController.h
//  MySatusItem
//
//  Created by user on 12/3/14.
//  Copyright (c) 2014 user. All rights reserved.
//

#import <Foundation/Foundation.h>
@protocol StatusItemDelegate;


@interface StatusItemController : NSView
{
    IBOutlet NSMenu *statuMenu;
    NSStatusItem *statusItem;
    NSImage *statusImage;
    NSImage *statusHighLightImage;
}
@end

@protocol StatusItemDelegate <NSObject>

-(IBAction)openMainConsole:(id)sender;


@end

 

//
//  StatusItemController.m
//  MySatusItem
//
//  Created by user on 12/3/14.
//  Copyright (c) 2014 user. All rights reserved.
//

#import "StatusItemController.h"

@implementation StatusItemController
-(void)awakeFromNib
{
    statusItem = [[NSStatusBar systemStatusBar]statusItemWithLength:NSSquareStatusItemLength];
    NSBundle *bundle = [NSBundle mainBundle];
    statusImage = [[NSImage alloc]initWithContentsOfFile:[bundle pathForResource:@"icon" ofType:@"tiff"]];
    statusHighLightImage = [[NSImage alloc]initWithContentsOfFile:[bundle pathForResource:@"icon@2x" ofType:@"tiff"]];
    
    [statusItem setImage:statusImage];
    [statusItem setAlternateImage:statusHighLightImage];
    
    [statusItem setMenu:statuMenu];
    [statusItem setToolTip:@"My custom Menu Item"];
    [statusItem setHighlightMode:YES];
    
}
@end

7. 剩下的就是在xib中把StatusItem跟StatusItemController关联起来

8. 最后把StatusMenu上的两个item跟程序里的方法关联起来,open main console就关联到App Delegate中的openMainConsole; quit关联到First Responder中的terminate:。

9. 结束后运行程序。

 

posted @ 2014-11-17 16:08  裸奔的小鸟  阅读(1275)  评论(0编辑  收藏  举报