轻松在 macOS 上构建菜单栏应用程序。同时支持 SwiftUI 和 AppKit。
打开 XCode,然后点击 File -> Add Package Dependencies...,在新窗口中,复制 https://github.com/boybeak/Tray.git
并粘贴到搜索框中。
使用前导入 Tray
。
import Tray
然后,在你的 AppDelegate
类中,声明一个类变量 private let tray = Tray()
。然后在 applicationDidFinishLaunching
中设置 tray 的参数,之后,安装它。
class AppDelegate: NSObject, NSApplicationDelegate {
private let tray: Tray!
func applicationDidFinishLaunching(_ notification: Notification) {
tray = Tray.install(named: "TrayIcon") { tray in
// config Tray here
// 1. setView
tray.setView(content: ContentView())
// tray.setView(view: ) or tray.setView(viewController: )
// Some other optional parameters:
// - behavior: NSPopover behavior, default is .transient;
// - level: NSPopover window level, default is .floating;
// - size: Size of NSPopover, default is nil, depends on the view you passed in.
// 2. If you do not need a view, you can set a left click event
tray.setOnLeftClick(onClick: {
self.onNewNoteAction()
return true // return true, If you handled event and prevent default action, the default action is show popover view if you set.
})
// 3. And also you can set a right click evnet
tray.setOnRightClick(onClick: {
return true // return true, If you handled event and prevent default action, the default action is show menu if you set.
})
// 4. If you need a menu for right click.
let menu = NSMenu()
let newNoteMenuItem = NSMenuItem(title: NSLocalizedString("Menu_item_new_note", comment: ""), action: #selector(onNewNoteAction), keyEquivalent: "")
let quitMenuItem = NSMenuItem(title: NSLocalizedString("Menu_item_quit", comment: ""), action: #selector(onQuitAction), keyEquivalent: "")
menu.addItem(newNoteMenuItem)
menu.addItem(quitMenuItem)
tray.setMenu(menu: menu)
}
}
@objc func onQuitAction() {
NSApplication.shared.terminate(nil)
}
}
Tray 图标尺寸:1x 为 18*18,2x 为 36*36,3x 为 54*54。
如果您正在使用 SwiftUI,您可以如下初始化 AppDelegate
@main
struct MyApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) var app: AppDelegate
var body: some Scene {
Settings {}
}
}
代码 Settings {}
将隐藏主窗口,如果你的应用只是一个 tray 应用程序。
这不适用于 macOS 15 及更高版本。请改用 NoLaunchWin。
如果你正在使用 swiftUI,你最好同时在 tray 和 swiftUI 的视图中设置大小。
// Tray install
Tray.install(content: ContentView(), size: CGSize(width: 320, height: 320))
struct ContentView: View {
var body: some View {
VStack {
Text("Hello, world!")
}
.frame(width: 320, height: 320)
}
}
配置大小后,看起来就正常了。
在 Info.plist 中添加一个选项:Application is agent(UIElement) - YES
谁在使用这个库?