Adding item to NSMenu with action selector preset

坚强是说给别人听的谎言 提交于 2019-12-08 07:32:32

问题


I'm new to Obj-C/Cocoa programming, and I'm having an issue trying to dynamically add menu items to an NSMenu instance and have the items action selector already set upon insertion.

I can, add the dynamic menu items fine, but the action selector doesn't trigger when the item is clicked via the menu.

The first line below is the line of code I am using to add the menu item. You can set I'm setting the action:(SEL)aSelector to the "openEchowavesURL" function.

This function is in the same controller class file and I've included the function definition below.

Am I just calling the wrong selector syntax or someting? Or what is the trick to get the menu item to call a selector when clicked?


[statusMenu insertItemWithTitle:[NSString stringWithFormat:@"%d - %@", convo.newMessagesCount, convo.ewName] action:@selector(openEchowavesURL:) keyEquivalent:@"" atIndex:0];

- (void)openEchowavesURL:(id)sender {
    // function details here
}

回答1:


If you want the action to be triggered against your object, you have to specify a target for the new NSMenuItem:

NSMenuItem *item = [statusMenu insertItemWithTitle:[NSString stringWithFormat:@"%d - %@", convo.newMessagesCount, convo.ewName] action:@selector(openEchowavesURL:) keyEquivalent:@"" atIndex:0];
[item setTarget:self]; // or whatever target you want

If you don't do it, then the NSResponder chain will be walked until an object responds to the selector.




回答2:


Actions need a target or else they get sent to nil and then new rules apply.



来源:https://stackoverflow.com/questions/1970135/adding-item-to-nsmenu-with-action-selector-preset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!