可可-如何设置状态栏应用程序左键单击事件



我是objective-c编程的新手,我现在正在尝试制作一个状态栏应用程序。

我只知道如何设置一个下拉菜单,以便在单击状态栏项时显示。

但是,我想要的是左键单击时显示panel,右键单击时显示menu,就像Bartender 2的行为方式一样。

我已经参考了这个演示,但我几乎无法弄清楚它的作用。

我使用xib来构建我的 UI。我有三个.xib文件:MainMenuPreferencesMainPanel

AppDelegate.h

#import <Cocoa/Cocoa.h>
@interface AppDelegate : NSObject <NSApplicationDelegate>
@property NSStatusItem *statusItem;
@end

AppDelegate.m

#import "AppDelegate.h"
#import "Menu.h" //Menu is a ViewController for Menu.xib
@interface AppDelegate ()
//@property (weak) IBOutlet NSWindow *window; //I don't know what is this for
@end
@implementation AppDelegate
@synthesize statusItem;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    // Insert code here to initialize your application
}
- (void)applicationWillTerminate:(NSNotification *)aNotification {
    // Insert code here to tear down your application
}
//I initiate my statusItem here
-(void)awakeFromNib{
    self.statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength];
    self.statusItem.title = @"T";
    // you can also set an image
    //self.statusBar.image =
    self.statusItem.highlightMode = YES;
//I tried to use these code to set the left click action
    [statusItem setTarget:self];
    [statusItem setAction:@selector(showMenu:)];
}
-(void)showMenu{
    Menu* menuVC = [[Menu alloc] initWithNibName:@"Menu" bundle:nil];
//Don't know what to do next...
}
@end

我尝试使用 [menuVC showWindow]; 但这是不对的。

有关在给定NSPoint绘制NSMenu的信息,请参阅这篇文章(使用 popUpContextMenu:withEvent:forView: 而不是 showWindow )。

我还要指出,在您链接的示例中,作者按照 MVC 模式将他的项目模块化为不同的组件。有一个用于菜单控制器和视图的组件(看起来他不只是显示一个NSMenu),以及面板控制器和视图。您可能需要考虑如何组织项目以遵循 MVC 的约定。

最新更新