创建菜单栏StatusItem及PopoverView

  1. 导入菜单栏icon图片

  2. 创建popover的页面

  3. AppDelegate.m中添加如下代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    #import "AppDelegate.h"
    #import "STPopoverViewController.h"

    @interface AppDelegate ()

    @property (nonatomic, strong) NSStatusItem *statusItem;
    @property (nonatomic, strong) NSPopover *popover;

    @end

    @implementation AppDelegate

    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {

    [self createStatusBar];
    }

    // 创建菜单栏Item及popover
    - (void)createStatusBar {

    // 创建NSStatusItem并显示在系统状态栏上
    self.statusItem = [[NSStatusBar systemStatusBar]statusItemWithLength:NSVariableStatusItemLength];
    [self.statusItem.button setImage:[NSImage imageNamed:@"StatusImage"]];

    // 添加点击事件
    self.statusItem.button.target = self;
    self.statusItem.button.action = @selector(clickStatusItem);

    // 创建popover
    self.popover = [[NSPopover alloc]init];
    self.popover.behavior = NSPopoverBehaviorTransient;
    self.popover.appearance = [NSAppearance appearanceNamed:NSAppearanceNameVibrantLight];
    self.popover.contentViewController = [[STPopoverViewController alloc]initWithNibName:@"STPopoverViewController" bundle:nil];
    }

    // 点击StatusItem
    - (void)clickStatusItem {

    if (self.popover.isShown) {
    // 如果正在显示,关闭popoverView
    [self.popover close];
    }else {
    // 如果关闭,弹出popoverView
    [self.popover showRelativeToRect:self.statusItem.button.bounds ofView:self.statusItem.button preferredEdge:NSRectEdgeMaxY];
    }
    }


    - (void)applicationWillTerminate:(NSNotification *)aNotification {
    // Insert code here to tear down your application
    }


    @end
  4. 运行,如下图所示