花了很多时间和错误,但我终于弄明白了。而不是使用Application is agent(UIElement)
,你使用NSApp.setActivationPolicy
。现在这是我的代码。在应用程序委托中:
var isWindow = false
class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate {
let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)
let popover = NSPopover()
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
NSApp.setActivationPolicy(.accessory)
if let button = statusItem.button {
button.image = NSImage(named: "StatusBarImage")
button.action = #selector(togglePopover(_:))
}
popover.contentViewController = MainViewController.loadController()
popover.delegate = self
popover.animates = false
popover.behavior = .transient
}
@objc func togglePopover(_ sender: Any?) {
if popover.isShown == true {
popover.performClose(sender)
} else if detachedWindowController.window!.isVisible {
detachedWindowController.window?.setIsVisible(false)
isWindow = true
} else if isWindow == true {
detachedWindowController.window?.setIsVisible(true)
} else {
if let button = statusItem.button {
popover.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
}
}
}
lazy var detachedWindowController: DetachedWindowController = {
let detachedWindowController = DetachedWindowController(windowNibName: "DetachedWindowController")
detachedWindowController.contentViewController = MainViewController.loadController()
return detachedWindowController
}()
func popoverShouldDetach(_ popover: NSPopover) -> Bool {
return true
}
func detachableWindow(for popover: NSPopover) -> NSWindow? {
return detachedWindowController.window
}
}
在DetachedWindowController
:
class DetachedWindowController: NSWindowController, NSWindowDelegate {
@IBOutlet var detachedWindow: NSWindow!
override func windowDidLoad() {
super.windowDidLoad()
detachedWindow.delegate = self
}
func windowWillClose(_ notification: Notification) {
isWindow = false
NSApp.setActivationPolicy(.accessory)
}
func windowDidBecomeMain(_ notification: Notification) {
if NSApp.activationPolicy() == .accessory {
NSApp.setActivationPolicy(.regular)
}
}
}