[英]Get index of NSMenuItem (sender) in parent menu
I'm having a NSMenu
( application dock menu ) and several items in it with the same action. 我有一个
NSMenu
( 应用程序停靠菜单 )和其中的几个项目具有相同的操作。
How can I figure out the index of the sender item (the one triggering the action) within its container menu? 如何在容器菜单中找出发件人项目的索引(触发操作的项目)? (I'm not interesting in the
title
, since that might be a duplicate) (我对
title
不感兴趣,因为那可能是重复的)
That's what I tried, but it keeps returning 0
(zero). 这就是我尝试过的,但它一直返回
0
(零)。
- (void)myAction:(id)sender
{
NSMenuItem* mi = (NSMenuItem*)sender;
int index = [[[mi parentItem] submenu] indexOfItem:mi];
NSLog(@"Clicked item with index : %d",index);
}
Any ideas? 有任何想法吗? (Is there any better approach to achieve the very same thing?)
(有没有更好的方法来实现同样的事情?)
You could use the menu items' representedObject
to store a reference to some object in your app. 您可以使用菜单项'
representedObject
来存储对应用中某个对象的引用。 In your case, you would probably use the document that the menu item refers to: 在您的情况下,您可能会使用菜单项引用的文档:
[aMenuItem setRepresentedObject:yourDocument];
You could then access the object in the action like so: 然后,您可以像这样访问操作中的对象:
- (void)myAction:(id)sender
{
NSMenuItem* mi = (NSMenuItem*)sender;
YourDocument* doc = (YourDocument*)[sender representedObject];
//do something with doc
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.