W. *_*ook 2 macos cocoa nspopover swift lsuielement
我正在编写一个NSPopover位于菜单栏右侧的 Mac 应用程序(Application is agent(UIElement)设置为YES)。我允许用户通过单击并向下拖动来分离弹出窗口,这会将应用程序放在窗口内。这工作正常;但是,当应用程序被拖出菜单栏并进入一个窗口时,我希望我的应用程序图标出现在 Dock 中,并在菜单栏的左侧显示特定于应用程序的菜单,就好像Application is agent(UIElement)设置为NO。相反,当窗口关闭并且应用程序返回到菜单栏中的弹出窗口时,我希望我的应用程序图标从 Dock 中消失并且不再在菜单栏的左侧显示特定于应用程序的菜单(Application is agent(UIElement)已设置回到YES)。
从这个问题,我明白Application is agent(UIElement)在运行时改变是不可能的。然而,给出的答案是在 Objective-C 中,最后一个函数似乎从 OS X 10.9 开始贬值了。如何使我的应用程序具有与Application is agent(UIElement)使用 Swift 在运行时更改相同的行为?
我知道显示应用windowDidBecomeMain程序图标/菜单栏菜单会发生在windowWillClose.
谢谢。
经过大量的反复试验,但我终于弄明白了。而不是使用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
}
}
Run Code Online (Sandbox Code Playgroud)
在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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
810 次 |
| 最近记录: |