简体   繁体   English

如何获得对我在可可粉中单击的菜单项的引用?

[英]How do I get a reference to the menu item i clicked on in Cocoa?

I have 2 nib files, MainMenu.xib, and another owned by an NSWindowController subclass. 我有2个nib文件MainMenu.xib,另一个是NSWindowController子类拥有的文件。 I've got 4 choices on a window panel, where only one of them can be selected (if another is selected, I want to set a check mark on the new one, and clear the other 3) 我在一个窗口面板上有4个选择,只能选择其中一个(如果选择了另一个,我想在新选择上设置一个复选标记,然后清除其他3个)

So I can easily tell which menu item was picked, by routing everything through the First Responder, and setting tags on the 4 menu choices. 因此,通过将所有内容路由到“第一响应者”并在4个菜单选项上设置标签,我可以很容易地知道选择了哪个菜单项。

Then, the selector which receives this action just looks at the tag, and takes the desired action. 然后,接收到此动作的选择器仅查看标签,并执行所需的动作。 And, as part of the IBAction, I get a reference to the sender...so I know how to set the checkmark on it. 并且,作为IBAction的一部分,我获得了对发件人的引用...所以我知道如何在其上设置对勾标记。 Clearing the checkmark on the other menu item could also be done by using an iVar to keep track of the most recent clicked on sender, and then I could do this, as suggested by the Cocoa docs: 也可以通过使用iVar跟踪最近单击的发件人来清除其他菜单项上的复选标记,然后按照Cocoa docs的建议执行此操作:

[currentItem setState:NSOffState];
[sender setState:NSOnState];

Now the problem boils down to the fact this is a document style app. 现在,问题归结为这是一个文档样式应用程序。 The menu selection is global, so I'd have to add logic whenever a new document window takes focus, and similar logic when a window loses focus. 菜单选择是全局的,因此每当新文档窗口获得焦点时,我就必须添加逻辑,而当窗口失去焦点时,则必须添加类似的逻辑。

I found a method I could implement -windowDidBecomeMain which tells me when my window controller became the main window. 我找到了一种可以实现-windowDidBecomeMain的方法,该方法告诉我窗口控制器-windowDidBecomeMain为主窗口。 But I dont see a corresponding method that tells me that the old window lost focus so it can clean up. 但是我没有看到相应的方法,该方法告诉我旧窗口失去了焦点,因此可以对其进行清理。

I found the answer here . 我在这里找到了答案。

The other methods are -windowDidResignMain and -windowWillClose 其他方法是-windowDidResignMain-windowWillClose

Edit: A better answer I had previously overlooked is to implement -(BOOL)validateMenuItem: I had seen this as a way of enabling or disabling menu items only via the return value, but I realized I could provide a side effect of setting the state as well. 编辑:我以前忽略的一个更好的答案是实现-(BOOL)validateMenuItem:我已经将其视为仅通过返回值启用或禁用菜单项的一种方式,但我意识到我可以提供设置状态的副作用也一样 So the NSWindowController is set up as the window delegate. 因此,NSWindowController被设置为窗口委托。 When the menu is opened, this method is called, and thus its always current for the active window. 菜单打开时,将调用此方法,因此该方法对于活动窗口始终是当前的。

Create a new object (inheriting from NSObject) to act as your controller object. 创建一个新对象(从NSObject继承)以用作您的控制器对象。 Instantiate that from the nib file and link the outlet to there. 从nib文件实例化该文件,然后将出口链接到那里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM