我正在进行Mac编程的初步学习。我只有一点iOS开发经验。
我需要构建一个非常简单的应用程序,它坐落在菜单栏中。
我想让它稍微自定义一些,所以决定使用NSWindow并将其附加到NSStatusItem。
我的AppDelegate如下:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
// Insert code here to initialize your application
float width = 30.0;
float height = [[NSStatusBar systemStatusBar] thickness];
NSRect viewFrame = NSMakeRect(0, 0, width, height);
statusItem = [[NSStatusItem alloc] init];
statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:30];
[statusItem setView:[[TSStatusBarItem alloc] initWithFrame:viewFrame]];
}
- (void)buttonClicked:(int)posx posy:(int)posy {
[_window setLevel:kCGMaximumWindowLevelKey];
opened = !opened;
NSLog(@"Window is shown: %i", opened);
[_window setFrameTopLeftPoint:NSMakePoint(posx, posy)];
if(opened == YES) {
_window.isVisible = YES;
} else {
_window.isVisible = NO;
}
}
这是 TSStatusBarItem 的代码。
- (void)drawRect:(NSRect)rect
{
// Drawing code here.
if (clicked) {
[[NSColor selectedMenuItemColor] set];
NSRectFill(rect);
}
NSImageView *subview = [[NSImageView alloc] initWithFrame:CGRectMake(3, 0, 20, 20)];
[subview setImage:[NSImage imageNamed:@"icon.png"]];
[self addSubview:subview];
}
- (void)mouseDown:(NSEvent *)event
{
NSRect frame = [[self window]frame];
NSPoint pt = NSMakePoint(NSMinX(frame), NSMinY(frame));
NSLog(@"X: %f and Y: %f", pt.x, pt.y);
[self setNeedsDisplay:YES];
clicked = !clicked;
[appDelegate buttonClicked:pt.x posy:pt.y];
}
窗口的显示和隐藏还不错,但只有当我点击StatusItem时才有效。我想添加当用户在菜单栏中选择其他项目或在窗口外部单击时隐藏窗口的行为(与典型的NSMenu应用程序类似)。
怎么做呢?如果您有任何简化我的代码的想法(抱歉,我是Mac编程的新手),请告诉我。