我想在 macOS 菜单栏中有一个项目占据栏的整个高度。这可以在例如 FaceTime 的 UI 中看到:
在我的尝试中,我只能让项目从菜单栏的 y 边缘延伸到 1pt:
(请注意,在带有缺口的菜单栏中,即使 FaceTime 也不会延伸到边缘,但它仍然比我的版本在
top
和 bottom
上进一步延伸 1pt)。
我已经尝试过
NSStatusItem
button
和(弃用)view
来让事情正常进行。我也试过 SwiftUI 的MenuBarExtra
导致上面第二个屏幕截图的简单示例:
final class StatusItemManager: ObservableObject {
var statusButtonItem: NSStatusItem?
var statusViewItem: NSStatusItem?
/// Note that this uses deprecated APIs -- I'd prefer to stay away from these if possible
func showViewStatusItem() {
statusViewItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
guard let statusViewItem else { return }
let iconView = NSHostingView(rootView: ItemView(title: "View"))
statusViewItem.view = iconView
statusViewItem.view?.frame = NSRect(x: 0, y: 0, width: 50, height: 40)
}
/// Non-deprecated, but still not working
func showButtonStatusItem() {
statusButtonItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
guard let statusButtonItem else { return }
let iconView = NSHostingView(rootView: ItemView(title: "Button"))
iconView.frame = NSRect(x: 0, y: 0, width: 50, height: 24)
statusButtonItem.button?.addSubview(iconView)
statusButtonItem.button?.action = #selector(menuBarButtonPressed)
statusButtonItem.button?.target = self
statusButtonItem.button?.frame = iconView.frame
}
struct ItemView: View {
var title: String
var body: some View {
Text(title)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.green)
}
}
@objc func menuBarButtonPressed(_ sender: Any?) {
print("pressed")
}
}
struct ContentView: View {
@StateObject var manager = StatusItemManager()
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundColor(.accentColor)
Text("Hello, world!")
}
.padding()
.onAppear {
manager.showButtonStatusItem()
manager.showViewStatusItem()
}
}
}