2011-07-22 111 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