2011-07-22 114 views
1

点击NSStatusItem时,弹出了一个自定义窗口。该代码基于MAAtachedwindow。一切都很好,但我无法找到一种方式来解除窗口,当用户点击另一个状态栏项目,或另一个应用程序的其他东西。关闭NSStatusItem的自定义窗口

这里是我创建的窗口代码:

statusItem = [[[NSStatusBar systemStatusBar] statusItemWithLength:width] retain]; 

    //setup custom status menu view 
    CGFloat height = [[NSStatusBar systemStatusBar] thickness]; 
    NSRect viewFrame = NSMakeRect(0.0f, 0.0f, width, height); 
    statusMenuView = [[[_ISStatusMenuView alloc] initWithFrame:viewFrame] retain]; 
    statusMenuView.offset = aOffset; 
    statusItem.view = statusMenuView; 

    //setup the window to show when clicked 
    NSRect contentRect = NSZeroRect; 
    contentRect.size = aView.frame.size; 
    statusMenuWindow = [[[NSWindow alloc] initWithContentRect:contentRect 
            styleMask:NSBorderlessWindowMask 
            backing:NSBackingStoreBuffered 
             defer:NO] retain]; 

    [statusMenuWindow setLevel:NSPopUpMenuWindowLevel]; 
    [statusMenuWindow setBackgroundColor:[NSColor clearColor]]; 
    [statusMenuWindow setMovableByWindowBackground:NO]; 
    [statusMenuWindow setExcludedFromWindowsMenu:YES]; 
    [statusMenuWindow setOpaque:NO]; 
    [statusMenuWindow setHasShadow:NO]; 
    [statusMenuWindow useOptimizedDrawing:YES]; 
    [[statusMenuWindow contentView] addSubview:aView]; 
    [statusMenuWindow setDelegate:self]; 

    statusMenuView.statusMenuWindow = statusMenuWindow; 

这里是我如何显示窗口:

- (void)centerView{ 
    NSRect menuFrame = self.window.frame; 
    NSRect windowFrame = self.statusMenuWindow.frame; 
    NSPoint menuPoint = NSMakePoint(NSMidX(menuFrame), NSMinY(menuFrame)); 
    menuPoint.x -= windowFrame.size.width*0.5f; 
    menuPoint.y -= windowFrame.size.height+self.offset; 
    [self.statusMenuWindow setFrameOrigin:menuPoint]; 
    [self.statusMenuWindow makeKeyAndOrderFront:self]; 
} 

我希望在windowDidResignKey委托方法会做的伎俩,但它不会因此配置而关闭。代表正在工作,因为windowDidMove确实运行。

- (void)windowDidResignKey:(NSNotification *)notification{ 
    NSLog(@"windowDidResignKey"); 
    [statusMenuView hideView]; 
} 

- (void)windowDidResignMain:(NSNotification *)notification{ 
    NSLog(@"windowDidResignMain"); 
} 

- (void)windowDidMove:(NSNotification *)notification{ 
    NSLog(@"windowDidMove"); 
} 

因此,要回顾一下,我怎么能隐藏自己的自定义窗口,当用户点击别的,标准状态栏菜​​单的工作方式?

编辑Popup例子后,我唯一缺少的是我不得不继承NSPanel并使其因此它可能成为关键窗口。

@interface Panel : NSPanel 
@end 

@implementation Panel 

- (BOOL)canBecomeKeyWindow{ 
    return YES; 
} 

@end 
+0

可能重复(http://stackoverflow.com/questions/4696689/hide-maattachedwindow-when-clicking-outside) – jtbandes

回答

4

你需要确保你的窗口可以成为关键窗口,并调用你的窗口的orderOut:方法时辞职的关键。你应该使用自定义的NSWindowController,如果你还没有,在这种情况下,你可以调用它的“close”方法来关闭你的窗口。

相反张贴了一堆代码,我建议你只是看一个窗口连接到一个状态项的这个优秀的,最近发布的例子: Shpakovski Popup Window Example

[点击外面时隐藏MAAttachedWindow]的
+0

该popover项目是完美的,谢谢! – keegan3d