2014-04-29 29 views
3

我玩弄一個想法,基本上我想要一個NSStatusItem與NSPopoverController。我閱讀了人們遇到的所有問題,但我只想嘗試一下。現在有沒有一種乾淨的方式來做到這一點?我見過的所有版本都至少有1年的歷史,並且非常帥氣。Popover NSStatusItem

這是我的方法,到目前爲止,但如果我點擊我的應用程序在狀態沒有任何反應......

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification 
{ 
    self.statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength]; 

    //[self.statusItem setView:view]; 
    [self.statusItem setTitle:@"Test"]; 
    [self.statusItem setHighlightMode:YES]; 
    [self.statusItem setAction:@selector(activatePopover:)]; 

} 


-(IBAction)activatePopover:(id)sender 
{ 
    BOOL isEnabled = NO; 

    if (isEnabled) { 
     [self.popover showRelativeToRect:NSMakeRect(0, 0, 50, 50) ofView:statusItem.view preferredEdge:NSMinYEdge]; 

    } else { 
     [self.popover close]; 
    } 
} 

任何想法如何得到這個運行?

謝謝

+0

'showRelativeToRect:ofView:preferredEdge'不會被調用,因爲'isEnabled'設置爲NO。 – Frank

+0

'2014-04-29 17:14:08.377 Aves [610:303] - [NSPopover showRelativeToRect:ofView:preferredEdge:]:提供無視圖。您必須提供一個視圖.' –

+0

我已將'popover'定義爲'@property(strong)IBOutlet NSPopover * popover;' –

回答

7

如果不使用狀態項目的自定義視圖,這將無法正常工作。如果您未設置自定義視圖,則view屬性將爲空(它僅返回自定義視圖,而不是當您僅使用setTitle時在內部使用的任何視圖NSStatusItem)。

不幸的是,根據Apple的文檔,如果您想使用NSPopover,則需要自行提供視圖並處理點擊。

我還沒有看到,包括這個正確處理(的狀態項的默認實現確實相當多的,你必須手動完成所有),並且還修復酥料餅wonkynesses一個完整的例子:

  • NSPopover,默認情況下,不會成爲關鍵窗口(某些控件將無法正常工作),除非你覆蓋NSPopover窗口的canBecomeKeyWindow
  • 正確駁回其他狀態項目菜單(你可以調用popUpStatusItemMenu一個空菜單正確集中您的狀態項目)
  • 繪製高亮背景drawStatusBarBackgroundInRect
  • 反應到左,右鼠標點擊
  • 使用NSRunningApplication.currentApplication.activateWithOptions,以確保您的狀態項目的所有窗口變爲有效(否則你的酥料餅會,不穩定,不能鍵盤輸入的接收器)
  • 駁回NSPopover與NSEvent.addGlobalMonitorForEventsMatchingMask(內置解僱機制popovers配不帶狀態的項目工作)
  • 拆卸終止狀態項與NSStatusBar.systemStatusBar.removeStatusItem

我希望能在不久的將來發布關於此的博客文章(注意:我正在使用RubyMotion,而不是Objective-C),它解釋了所有這些問題,並希望爲創建菜單提供更簡單的基礎。如果我寫這篇文章,我會更新這個評論。

+2

MY HOLY GOD !!!爲什麼Objective C和OS X的發展太強大,難以理解? –

+1

調用[NSRunningApplication。currentApplication activateWithOptions:NSApplicationActivateIgnoringOtherApps];之後showRelativeToRect爲我工作。 – dlinsin

1

代碼:

(void)initializeStatusBarItem 
{ 
    self.statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength]; 

    NSImage* image = [NSImage imageNamed:@"image"]; 
// [image setTemplate:YES]; 
    self.statusItem.button.image = image; 

    self.statusItem.highlightMode = NO; 
    self.statusItem.button.action = @selector(statusBarItemDidClick:); 
} 

- (void)statusBarItemDidClick:(NSStatusBarButton *)sender{ 
    MainViewController *mainView = [[MainViewController alloc] init]; 
    self.popoverView = [[NSPopover alloc] init]; 
    [self.popoverView setContentViewController:mainView]; 
    self.popoverView.contentSize = CGSizeMake(300, 400); 
    self.popoverView.behavior = NSPopoverBehaviorTransient; 
    [self.popoverView showRelativeToRect:sender.bounds ofView:sender preferredEdge:NSMaxYEdge]; 


} 
+0

謝謝!這幫了很多,豎起大拇指! 1+ – Lucasware