我目前正在开发一个“仅菜单栏”项目,我需要在菜单栏应用程序的子菜单中列出所有已安装的卷。我想出了如何打印()所有已安装的卷,但我需要帮助子菜单(没有.xib或.storyboard工作) 这是我的“listVolumes func”
func listVolumes(sender: NSMenuItem) {
let keys = [NSURLVolumeNameKey, NSURLVolumeIsRemovableKey, NSURLVolumeIsEjectableKey]
let paths = NSFileManager().mountedVolumeURLsIncludingResourceValuesForKeys(keys, options: [])
if let urls = paths {
for url in urls {
if let components = url.pathComponents
where components.count > 1
&& components[1] == "Volumes" {
print(url)
}
}
}
}
以下是“菜单栏应用”的代码
let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-2)
func applicationDidFinishLaunching(aNotification: NSNotification) {
if let button = statusItem.button {
button.image = NSImage(named: "StatusBarButtonImage")
}
let menu = NSMenu()
menu.addItem(NSMenuItem(title: "Volumes", action: Selector("volumes:"), keyEquivalent: ""))
menu.addItem(NSMenuItem.separatorItem())
menu.addItem(NSMenuItem(title: "Help", action: Selector("help:"), keyEquivalent: ""))
menu.addItem(NSMenuItem.separatorItem())
menu.addItem(NSMenuItem(title: "Quit", action: Selector("terminate:"), keyEquivalent: "q"))
statusItem.menu = menu
}
所以我的问题是,如何创建一个包含所有已安装驱动器的子菜单(仅以编程方式)
答案 0 :(得分:1)
您必须将子菜单设置为volumes
菜单项,例如
let volumesMenuItem = NSMenuItem(title: "Volumes", action: Selector("volumes:"), keyEquivalent: "")
menu.addItem(volumesMenuItem)
let volumesMenu = NSMenu(title: "Volumes")
volumesMenuItem.submenu = volumesMenu
我建议您从listVolumes()
函数返回一个名称数组,然后您可以将菜单项添加到volumesMenu
,假设volumes
包含名称
for volumeName in volumes {
volumesMenu.addItem(NSMenuItem(title: volumeName, action: Selector("selectVolume"), keyEquivalent: ""))
}