无法隐藏状态栏中的NSStatusItem?技术问题求助
问题分析与解决方案
核心问题
你每次调用NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)都会创建全新的NSStatusItem实例,修改的是这个新实例的可见性,完全没操作AppDelegate里最初创建的那个状态栏图标,所以原图标自然不会消失。
解决方案
步骤1:确保AppDelegate的statusItem是可访问的类属性
确认AppDelegate中的statusItem为类级别的属性(用于保存创建的状态栏实例):
class AppDelegate: NSObject, NSApplicationDelegate { var statusItem: NSStatusItem? func applicationDidFinishLaunching(_ notification: Notification) { statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength) statusItem?.button?.image = NSImage(systemSymbolName: "paperplane.fill", accessibilityDescription: nil) if let menu = menu { statusItem?.menu = menu } } }
步骤2:在偏好设置控制器中操作原statusItem实例
修改hideicon方法,直接获取AppDelegate中保存的状态栏实例,而非创建新实例:
@IBAction func hideicon(_ sender: NSButton) { guard let appDelegate = NSApplication.shared.delegate as? AppDelegate else { return } appDelegate.statusItem?.isVisible = (sender.state != .on) }
可选:持久化设置(重启应用保持状态)
如果需要重启应用后保留隐藏/显示状态,可将设置存入UserDefaults:
偏好设置控制器修改:
@IBAction func hideicon(_ sender: NSButton) { let shouldHide = (sender.state == .on) UserDefaults.standard.set(shouldHide, forKey: "HideStatusIcon") guard let appDelegate = NSApplication.shared.delegate as? AppDelegate else { return } appDelegate.statusItem?.isVisible = !shouldHide }
AppDelegate启动时读取设置:
func applicationDidFinishLaunching(_ notification: Notification) { statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength) statusItem?.button?.image = NSImage(systemSymbolName: "paperplane.fill", accessibilityDescription: nil) if let menu = menu { statusItem?.menu = menu } let shouldHide = UserDefaults.standard.bool(forKey: "HideStatusIcon") statusItem?.isVisible = !shouldHide }
内容的提问来源于stack exchange,提问作者fantasticproposal
相关产品推荐
相关产品推荐

