Reputation: 265
I was reading this apple documentation for MenuBarExtra in macos and it states:
When necessary, the system hides menu bar extras to make room for app menus. Similarly, if there are too many menu bar extras, the system may hide some to avoid crowding app menus.
I am using Appkit implementation for MenuBarExtras and wanted to know, how to identify if the system has hidden/unhidden my menuBarExtra. Is there some event that is received when the system hides it?
Upvotes: -1
Views: 247
Reputation: 2712
You can use this to listen for window changing its state (visible/hidden)
NotificationCenter.default.addObserver(forName: NSWindow.didChangeOcclusionStateNotification, object: nil, queue: nil) { notification in
print("isVisible:", (notification.object as! NSWindow).isVisible)
}
Upvotes: 1
Reputation: 52565
First, you'll need a reference to the NSWindow
that holds that status item. You can get that like this:
statusItem.button?.window
Then, you'll want to listen to some NSNotification
s related to that window. For example, we listen to:
NSWindow.didChangeScreenNotification
NSWindow.didMoveNotification
NSWindow.didResizeNotification
NSWindow.didChangeOcclusionStateNotification
Theoretically, only the last one should be required (https://developer.apple.com/documentation/appkit/nswindow/1419549-didchangeocclusionstatenotificat), actually, but we have some use cases for the others as well.
Then, upon receiving the notification, you can check the occlusion by doing:
window.occlusionState.contains(.visible)
Upvotes: 1