我正在为 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 编码的新手)- 请说。