美文网首页
Mac Dev Part 2 - Menu Bar - Even

Mac Dev Part 2 - Menu Bar - Even

作者: 遇见Miu | 来源:发表于2019-03-01 18:43 被阅读1次

    时间总是挤出来的

    继续昨天的Menu Bar,实现Menu Bar点击其他位置也会收起

    1.创建EventMonitor监听鼠标点击事件

    EventMonitor.swift

    class EventMonitor {
        private var monitor: AnyObject?
        private var mask: NSEvent.EventTypeMask
        private var handler: (NSEvent?) -> ()
        
        init(mask: NSEvent.EventTypeMask, handler: @escaping (NSEvent?) -> ()) {
            self.mask = mask
            self.handler = handler
        }
        
        // 反初始化(释放资源)
        deinit {
            stop()
        }
        
        func start() {
            // 监听全局的鼠标事件
            monitor = NSEvent.addGlobalMonitorForEvents(matching: mask, handler: handler) as AnyObject
        }
        
        func stop() {
            if monitor != nil {
                NSEvent.removeMonitor(monitor!)
                monitor = nil
            }
        }
    }
    
    

    展开下拉视图后,点击屏幕其他处可以收起

    AppDelegate.swift

        let popover = NSPopover()
        var eventMonitor: EventMonitor?
        
        func applicationDidFinishLaunching(_ aNotification: Notification) {
            
            if let button = statusItem.button {
                button.image = NSImage(named: "statusItembutton")
                button.action = #selector(showDetail(sender:))
            }
            
            popover.contentViewController = DetailViewController.loadFromNib()
            // 左右键均触发
            eventMonitor = EventMonitor(mask: [.leftMouseUp, .rightMouseUp], handler: { (event) in
                if self.popover.isShown {
                    self.closePopover(sender: event)
                }
            })
        }
        
        func showPopover(sender: AnyObject?) {
            if let button = statusItem.button {
                popover.show(relativeTo: button.bounds, of: button, preferredEdge: .minY)
            }
            eventMonitor?.start()
        }
        
        func closePopover(sender: AnyObject?) {
            popover.performClose(sender)
            eventMonitor?.stop()
        }
        
        @objc func showDetail(sender: NSStatusBarButton) {
            if popover.isShown {
                closePopover(sender: sender)
            } else {
                showPopover(sender: sender)
            }
        }
    

    相关文章

      网友评论

          本文标题:Mac Dev Part 2 - Menu Bar - Even

          本文链接:https://www.haomeiwen.com/subject/yadjuqtx.html