views:

181

answers:

3

I am looking for some code to make a Menu appear next to a button when it is clicked. What code would I need for this?

Sorry if this sounds a bit vague.

+3  A: 

Why not use NSPopUpButton?

Peter Hosey
How would I make the Pop up button not show the arrows at the end and look like a normal button with an image inside?
Joshua
Sorted out it not showing arrows and look like a normal button but how do I it show as a image instead of text?
Joshua
Why do you want to hide that it's a pop-up? How is the user supposed to know that clicking it will pop up a menu?
Peter Hosey
Don't worry I've sorted out what I wanted to do.
Joshua
A: 

If you really need to roll this yourself, rather than using one of the built-in controls that shows a menu, you can create an NSPopupButtonCell and use that to show the NSMenu:

NSPopUpButtonCell *popupCell = [[NSPopUpButtonCell alloc] initTextCell:@"" pullsDown:YES];
[popupCell setMenu:yourMenu];
[popupCell trackMouse:event inRect:[yourButton bounds] ofView:yourButton untilMouseUp:YES];
[popupCell release];

You'd want to adjust the pullsDown:, inRect:, and ofView: arguments as necessary to position the menu the way you want.

smorgan
I wouldn't reuse a popup button cell just for a menu, especially when you can cal `popUpContextMenu`.
Marc Charbonneau
I wasn't aware that the popUpContextMenu methods allowed for precise control of menu positioning (including things like handling being near the edge of the screen correctly by repositioning relative to a different edge of the view).
smorgan
+1  A: 

NSPopupButton was my first thought as well. It's how apps with the "action gear" buttons accomplish their menus.

If you do have something else in mind though, look at NSMenu's +popUpContextMenu:withEvent:forView:. Just hook an action method up to your button, create an NSMenu and populate it with NSMenuItems, and send it to this method along the the current event from NSApplication's currentEvent getter.

Marc Charbonneau
How would you control the details of the menu location with that approach?
smorgan
You'd want to pass it an NSEvent with the appropriate location as the event's -locationInWindow
Matt Ball