20

I have seen a lot of applications with a Menubar Item or applications with only a Menubar interface.

There are some tutorials and stuff on the internet showing you how to accomplish that. But the thing is, those do only have clickable index rows in them.

I would want to have a NSPopover appear when you click the Menubar Icon / Item. Anybody who knows how to make this?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Jacob
  • 1,310
  • 1
  • 15
  • 29

1 Answers1

58

I don't know if it can be done with a standard status bar item. Using a custom view for the menulet it's relatively easy.

Create a status bar item with a custom view:

item = [[NSStatusBar systemStatusBar] statusItemWithLength:thickness];
view = [[CustomView alloc] initWithFrame:(NSRect){.size={thickness, thickness}}];
[item setView:view];        

Your custom view needs to detect mouse clicks:

- (void)mouseDown:(NSEvent *)event {
   ...
}

And finally, at some point after detecting the mouse click, show/hide the popover.

if (/* menulet is active */) {
    [popover showRelativeToRect:/* menulet view frame */
                         ofView:/* menulet view */
                  preferredEdge:NSMinYEdge];
} else {
    [popover performClose:nil];
}

You need a bit of NSWindow swizzling to get text fields working inside the popover.

I've prepared a minimal Xcode project with these ideas and some glue: PopoverMenulet.

djromero
  • 19,551
  • 4
  • 71
  • 68
  • You, sir, are a saint. Thank you for the awesome answer. – Dan Loewenherz Oct 29 '11 at 21:07
  • Thanks! Very nice, this is how all answers should be. – Jacob Nov 21 '11 at 18:05
  • Using this method, I can't get a text field to activate. It seems like it's inactive, like when a window with a text field is not the active window. Anyone know how to activate a text field in this case? – Elbimio Mar 24 '12 at 21:38
  • It's a known bug that textfields aren't active in this situation, see http://stackoverflow.com/questions/7214273/nstextfield-on-nspopover/7794324#7794324 – Tim Apr 09 '12 at 21:41
  • Have you delete your XCode Project ? – Matthieu Riegler Jan 23 '13 at 09:41
  • Opps, sorry. I just renamed my user in github. I forgot to update this link. It's correct now. – djromero Jan 23 '13 at 10:58
  • Thanks for your great solution. One question. When the popover is active, I would like it to dismiss when I click another window, switch application etc. Currently I have to click the *NSStatusItem* to dismiss it. How should this be implemented? – dhrm Oct 02 '13 at 13:10
  • The only way I can think right now is implementing an event tap. A pass-trough monitor that receives every click and if it's not inside the popover dismiss it. – djromero Oct 02 '13 at 20:10
  • Thank djromero, It is awesome. – quang thang Feb 11 '15 at 07:00