3.3 NSStatusBar NSStatusBar位于顶部状态栏的右侧,启用设置后会常驻任务栏显示相关信息或进行某操作。
3.3.1 基本声明 打开AppDelegate.swift文件,修改如下所示代码:
var item: NSStatusItem!
func applicationDidFinishLaunching(_ aNotification: Notification) {
var statusBar = NSStatusBar.system
item = statusBar.statusItem(withLength: 23)
item.button?.target = self
item.button?.action = #selector(statusListener)
item.image = NSImage(named: "user")
let menu = NSMenu()
let menuItemOne = NSMenuItem(title: "Test1", action: #selector(statusListener), keyEquivalent: "T")
menuItemOne.target = self
menuItemOne.keyEquivalentModifierMask = .shift
let menuItemTwo = NSMenuItem(title: "Test2", action: #selector(statusListener), keyEquivalent: "Y")
menuItemTwo.target = self
menuItemTwo.keyEquivalentModifierMask = .shift
menu.addItem(menuItemOne)
menu.addItem(menuItemTwo)
let test2SubMenu = NSMenu()
let menuItemTwoSubOne = NSMenuItem(title: "Sub1", action: #selector(statusListener), keyEquivalent: "U")
menuItemTwoSubOne.target = self
menuItemTwoSubOne.keyEquivalentModifierMask = .shift
test2SubMenu.addItem(menuItemTwoSubOne)
menuItemTwo.submenu = test2SubMenu
item.menu = menu
}
说明:NSStatusItem系NSStatusBar内菜单的管理类,可用来设置菜单及其子项;NSStatusBar系NSStatusItem的管理类,自身也可设置多项属性(如图片等)。
运行截图
|