2015-09-20 53 views
0

對於我的小型Mac菜單欄應用程序,我希望popover的行爲是暫時的,所以當它失去焦點時,它將關閉。這適用於:Xcode Swift OS X popover行爲

popover.behavior = NSPopoverBehavior.Transient 

但它只能工作一次,所以你第二次點擊其他地方彈出保留。我將代碼放在func applicationDidFinishLaunching(notification: NSNotification)中,但將它放在該類中的該函數之外不起作用。我怎樣才能始終使用這種行爲?

我使用Swift(2.0)的Xcode 7.0。

回答

2

您最好將行爲保留爲默認值,即NSPopoverBehaviorApplicationDefined,並且實現必要的函數來處理它。正如Apple文檔中所述,其他兩種行爲的情況並不明確。你可以做如下:

detector = NSEvent.addGlobalMonitorForEventsMatchingMask([NSEventMask.LeftMouseDownMask, NSEventMask.RightMouseDownMask], handler: { [weak self] event in 
       self?.hidingFunction() 
      }) 

離開的時候/右鍵現在你實現你做出上述呼籲的hidingFunction()在同一個班級進行
此註冊了montior到全球事件的處理程序被指定爲自我。
此功能將關閉酥料餅和和刪除監視器創建

func hidingFunction(){ 
popover.close() 
if let temp: AnyObject = detector { // using if let to be sure it was intialized 
    NSEvent.removeMonitor(temp) 
} 

探測器只是一個變量名可以命名爲任何你想要在類的頂部,類型的任何對象之前定義它

var detector: AnyObject? 
0

更新斯威夫特3

var detector: Any? 

detector = NSEvent.addGlobalMonitorForEvents(matching:[NSEventMask.leftMouseDown, NSEventMask.rightMouseDown], handler: { [weak self] event in 
     self?.hidingFunction() 
    }) 

func hidingFunction() { 
    popover.close() 
    if let temp: Any = detector { // using if let to be sure it was intialized 
     NSEvent.removeMonitor(temp) 
    } 
}