找到一个解决办法,菜单栏popover的代码我是看Kavsoft的视频抄的的,这块是AppKit的代码写的,并没有完全理解。只需要调整下popover.contentViewController?.view.window?.makeKey()这行代码的位置即可,把这行代码从setUpMacMenu中,挪到menuButtonAction的else中,这样还可以解决另一个问题:点击弹出区域外的位置,菜单弹出区域不会自动关闭。
代码:
class AppDelegate: NSObject, ObservableObject, NSApplicationDelegate {
private var statusItem: NSStatusItem?
private var popover = NSPopover()
func applicationDidFinishLaunching(_ notification: Notification) {
setUpMacMenu()
}
func setUpMacMenu() {
popover.animates = true
popover.behavior = .transient
popover.contentViewController = NSViewController()
popover.contentViewController?.view = NSHostingView(rootView: HomeView())
//popover.contentViewController?.view.window?.makeKey()
statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
if let menuButton = statusItem?.button {
menuButton.image = .init(systemSymbolName: "d.circle.fill", accessibilityDescription: nil)
menuButton.action = #selector(menuButtonAction)
}
}
@objc func menuButtonAction() {
if popover.isShown {
popover.performClose(nil)
}else {
if let menuButton = statusItem?.button {
popover.show(relativeTo: menuButton.bounds, of: menuButton, preferredEdge: .minY)
popover.contentViewController?.view.window?.makeKey()
}
}
}
}