在Cocoa OSX中以编程方式实例化NSPopUpButtonCell

时间:2009-12-18 01:25:56

标签: cocoa macos nspopupbuttoncell

我有一个openGL GUI界面,我需要有一个弹出菜单,当我在openGL显示屏中按下某个按钮时会调用该菜单。我想显示一个类似于按下NSPopUPButton时弹出的菜单,但我不能使用Cocoa按钮本身。似乎完成此任务的最佳方法是使用NSPopupButtonCell。我不能在这里发布我的代码因为我在Lisp中编写代码并通过一个客观的C桥访问Cocoa但我只是想看看下面的pseduo代码是否应该显示菜单或者是否有明显的缺陷逻辑:

• 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.

这些方法都没有成功获得任何类型的菜单。有没有其他方法可以编程弹出单元格中包含的菜单?

2 个答案:

答案 0 :(得分:3)

我认为您正在寻找NSCell

trackMouse:inRect:ofView:untilMouseUp:方法
[theCell trackMouse:[NSApp currentEvent] inRect:NSZeroRect ofView:theView untilMouseUp:YES];

答案 1 :(得分:0)

我认为您最好使用普通NSMenu并致电+[NSMenu popUpContextMenu:withEvent:forView:]。如果您的目标只是10.6及更高版本,您还可以查看-[NSMenu popUpMenuPositioningItem:atLocation:inView:],这样您就可以更好地控制菜单的位置。只需在视图中实现mouseDown:,构建一个菜单(或从nib文件加载它),然后显示它,NSMenu应该从那里处理所有细节。只需确保设置每个NSMenuItem的目标和操作,以便在选择项目时正确调用操作方法。