如何显示NSStatusBar项并隐藏停靠栏图标?

时间:2017-07-24 23:18:08

标签: swift xcode macos user-interface cocoa

我已尝试设置"应用程序是代理"为1但状态栏项目消失。设置为0时,状态栏项目和停靠栏图标都会显示。如何显示状态栏项但隐藏停靠栏图标?

我已在awakeFromNib()中的applicationDidFinishLaunching()AppDelegate.swift中尝试了以下内容:

//class scope    
let statusItem = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength)

//function scope    
self.statusItem.image = NSImage(named: "myImage")
let menu = NSMenu(title: "MyApp-Menu")
let menuItem = NSMenuItem(title: "title", action: nil, keyEquivalent: "")
menu.addItem(menuItem)
self.statusItem.menu = menu

2 个答案:

答案 0 :(得分:0)

已针对Mac OS 10.14进行了更新

在AppDelegate中

let statusItem = NSStatusBar.system.statusItem(withLength:NSStatusItem.squareLength)

func applicationDidFinishLaunching(_ aNotification: Notification) {
    if let button = statusItem.button {
        button.image = NSImage(named:NSImage.Name("StatusBarButtonImage"))
        button.action = #selector(launchFromTray)
    }
    constructMenu()
}

func constructMenu() {
    let menu = NSMenu()
    menu.addItem(NSMenuItem.separator())
    menu.addItem(NSMenuItem(title: "Show", action: #selector(launchFromTray), keyEquivalent: "w"))
    menu.addItem(NSMenuItem(title: "Quit", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q"))

    statusItem.menu = menu
}

现在应该将Application is agent (UIElement)设置为YES。应该工作正常,希望这会帮助某人

答案 1 :(得分:0)

您想要隐藏停靠栏图标,您必须设置"应用程序是代理商"到"是"或者您可以将应用程序设置为UIElement Application:

 ProcessSerialNumber psn = { 0, kCurrentProcess };
 OSStatus rt = TransformProcessType(&psn, kProcessTransformToUIElementApplication);

根据您提供的代码部分,我认为您说"状态栏项目消失了"并没有真正消失,只是菜单消失了。除非您编写错误的代码,否则状态栏不会消失,但您的代码看起来很好。

如果我认为正确,菜单会消失,因为该应用是代理商应用。你需要做的就是再次成为一个UI元素应用程序:

ProcessSerialNumber psn = { 0, kCurrentProcess };
    OSStatus returnCode = TransformProcessType(&psn, kProcessTransformToForegroundApplication);

运行代理应用时,您无法显示菜单栏。只需在代理应用和菜单栏之间选择一个。

Agents include background-only applications, faceless background-only applications, and UI elements, but is not a full blown application with a menu bar