我正在编写一个使用popover
的MacOS菜单栏应用程序。我依靠许多教程来使事情进展。该应用程序不使用情节提要或Interface Builder。
计划是在右键单击时显示一个菜单,或者在左键单击时显示一个弹出框。
非常简短,代码看起来像这样:
class AppDelegate: NSObject, NSApplicationDelegate {
var popover=NSPopover()
var statusBarItem: NSStatusItem!
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Popover & Content View
let contentView = ContentView()
self.popover.contentViewController = NSHostingController(rootView: contentView)
// Menu
self.statusBarItem = NSStatusBar.system.statusItem(withLength: 18)
if let statusBarButton = self.statusBarItem.button {
statusBarButton.title = "☰"
statusBarButton.action = #selector(togglePopover(_:))
statusBarButton.sendAction(on: [.leftMouseUp, .rightMouseUp])
}
}
@objc func togglePopover(_ sender: AnyObject?) {
let statusBarButton=self.statusBarItem.button!
let event = NSApp.currentEvent!
event.type == NSEvent.EventType.rightMouseUp ? print("Right-Click") : print("Left-Click")
func show(_ sender: AnyObject) {
self.popover.show(relativeTo: statusBarButton.bounds, of: statusBarButton, preferredEdge: NSRectEdge.maxY)
}
func hide(_ sender: AnyObject) {
popover.performClose(sender)
}
self.popover.isShown ? hide(sender as AnyObject) : show(sender as AnyObject)
}
}
我可以使弹出窗口起作用,但是当右键单击该按钮时,我想如何显示一个不同的真实菜单。我该怎么办?