如何在状态栏应用程序中定位 NSPopover (macOS)
How to position NSPopover in status bar application (macOS)
我使用 SwiftUI 创建了一个 macOS 状态栏应用程序,我终于让一切都按照我想要的方式工作。唯一的问题是,当我在全屏模式下使用它时,状态栏会隐藏并且弹出菜单会被切断。有什么想法吗?
MyApp.swift:
import SwiftUI
@main
struct MyApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) var delegate;
var body: some Scene {
Settings {
ContentView()
}
}
}
class AppDelegate: NSObject,NSApplicationDelegate {
var statusItem: NSStatusItem!
var popOver: NSPopover!
func applicationDidFinishLaunching(_ notification: Notification){
let contentView = ContentView()
let popOver = NSPopover();
popOver.behavior = .transient
popOver.animates = true
popOver.contentViewController = NSHostingController(rootView: contentView)
popOver.setValue(true, forKeyPath: "shouldHideAnchor")
self.popOver = popOver
self.statusItem = NSStatusBar.system.statusItem(withLength: CGFloat(NSStatusItem.variableLength))
if let MenuButton = self.statusItem.button {
MenuButton.image = NSImage(systemSymbolName: "display.2", accessibilityDescription: nil)
MenuButton.action = #selector(MenuButtonToggle)
}
}
@objc func MenuButtonToggle(_ sender: AnyObject){
if let button = self.statusItem.button {
if self.popOver.isShown{
self.popOver.performClose(sender)
}else {
self.popOver.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
self.popOver.contentViewController?.view.window?.makeKey()
}
}
}
}
在您的代码中,只需添加一个比弹出窗口本身大的“随机”尺寸。
我认为发生这种情况是因为没有立即计算弹出窗口的大小,所以其中存在竞争条件,但这对我来说似乎很有效
popOver.contentSize = NSSize(width: 600, height: 1)
我使用 SwiftUI 创建了一个 macOS 状态栏应用程序,我终于让一切都按照我想要的方式工作。唯一的问题是,当我在全屏模式下使用它时,状态栏会隐藏并且弹出菜单会被切断。有什么想法吗?
MyApp.swift:
import SwiftUI
@main
struct MyApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) var delegate;
var body: some Scene {
Settings {
ContentView()
}
}
}
class AppDelegate: NSObject,NSApplicationDelegate {
var statusItem: NSStatusItem!
var popOver: NSPopover!
func applicationDidFinishLaunching(_ notification: Notification){
let contentView = ContentView()
let popOver = NSPopover();
popOver.behavior = .transient
popOver.animates = true
popOver.contentViewController = NSHostingController(rootView: contentView)
popOver.setValue(true, forKeyPath: "shouldHideAnchor")
self.popOver = popOver
self.statusItem = NSStatusBar.system.statusItem(withLength: CGFloat(NSStatusItem.variableLength))
if let MenuButton = self.statusItem.button {
MenuButton.image = NSImage(systemSymbolName: "display.2", accessibilityDescription: nil)
MenuButton.action = #selector(MenuButtonToggle)
}
}
@objc func MenuButtonToggle(_ sender: AnyObject){
if let button = self.statusItem.button {
if self.popOver.isShown{
self.popOver.performClose(sender)
}else {
self.popOver.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
self.popOver.contentViewController?.view.window?.makeKey()
}
}
}
}
在您的代码中,只需添加一个比弹出窗口本身大的“随机”尺寸。
我认为发生这种情况是因为没有立即计算弹出窗口的大小,所以其中存在竞争条件,但这对我来说似乎很有效
popOver.contentSize = NSSize(width: 600, height: 1)