1

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.

Joshua
  • 15,200
  • 21
  • 100
  • 172

3 Answers3

4

Why not use NSPopUpButton?

Peter Hosey
  • 95,783
  • 15
  • 211
  • 370
  • 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 May 22 '09 at 05:36
  • 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 May 22 '09 at 05:42
  • 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 May 22 '09 at 05:49
  • Don't worry I've sorted out what I wanted to do. – Joshua May 22 '09 at 06:18
2

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
  • 40,399
  • 3
  • 75
  • 82
0

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
  • 20,228
  • 3
  • 47
  • 55
  • I wouldn't reuse a popup button cell just for a menu, especially when you can cal `popUpContextMenu`. – Marc Charbonneau May 21 '09 at 22:27
  • 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 May 21 '09 at 22:44