Search code examples
swiftmacoscocoansstatusitemnsstatusbar

Detect when a NSStatusItem has been removed via drag and drop


One can set a NSStatusItem's behaviour property to removalAllowed (NSStatusItemBehaviorRemovalAllowed) Then a user can remove the item from the status bar using drag and drop.

removing the WiFi status item from the status bar

Example: removing the WiFi status item from the status bar

However, I am unable to detect when the statusbar is being removed so I can remember it and not show it the next time the user starts the app. There is no delegate or notification and the statusBar property is readonly so I can't override the setter.

Any idea? :)


Solution

  • The documentation for NSStatusItemBehaviorRemovalAllowed says:

    Upon removal, the item’s visible property changes to NO. This change is observable using key-value observation.

    So you could add a KVO observer for that property, and if it changes to NO (and assuming you didn't set it to NO), don't show your status bar item on future launches.


    That said, in testing this out: the system handles this for you fairly well. When you create your status bar item, don't set the visible property, and set an autosaveName. If the user removes your item from the status bar, the system writes that to the app's preferences in ~/Library/Preferences, and your status bar item won't be visible on future launches.

    To restore the visibility, manually set the visible property to YES.