Programmatically instantiating a NSPopUpButtonCell in Cocoa OSX

576 views Asked by At

I have an openGL GUI interface and I need to have a popup menu that will be called when this a certain button is pressed in my openGL display. I want to display a menu similar to the one that pops up when you press an NSPopUPButton but I cannot use the Cocoa button itself. It seems that the best way to accomplish this is to use the NSPopupButtonCell. I cannot post my code here because I am writing the code in Lisp and accessing the Cocoa through an Objective-C bridge but I just wanted to see if the following pseudo code seems like it should display the menu or if there is an obvious flaw in my logic:

• Pseudo Code for function that is called when button is pressed:
• Initialize an NSPopUpButtonCell Using initTextCell: "test" pullsDown: NO
• allocate an NSMenu using alloc
• add two menu items using addItem:
• set the menu of the popUpButtonCell to be the menu that was just allocated using setMenu:
• Next I tried two methods to try and get the menu to actually be displayed,
  first I tried using drawWithFrame:inView: and when that did not work I also tried 
  using drawBezelWithFrame:inView: eventhough the docs said not to use but I just 
  tried it out of desperation.
• finally, when the draw methods did not work I tried using performClick: on the 
  popupButtonCell to try and simulate the click.

None of these methods were successful in getting any sort of menu to be displayed. Is there some other way to programmatically pop up the menu contained in the cell?

2

There are 2 answers

0
0xced On BEST ANSWER

I think you are looking for the trackMouse:inRect:ofView:untilMouseUp: method of NSCell

[theCell trackMouse:[NSApp currentEvent] inRect:NSZeroRect ofView:theView untilMouseUp:YES];
2
Brian Webster On

I think you would be better off using a plain NSMenu and calling +[NSMenu popUpContextMenu:withEvent:forView:]. If you're targetting only 10.6 and later, you might also check out -[NSMenu popUpMenuPositioningItem:atLocation:inView:], which gives you a little more control over the positioning of the menu. Just implement mouseDown: in your view, construct a menu (or load it from a nib file), and display it, and NSMenu should take care of all the details from there. Just make sure that the target and action for each NSMenuItem is set so that the action method gets called correctly when an item is selected.