Creating a Dynamic NSMenuItems Account

I am currently struggling with a dynamic interface in Mac OS X. I have created a menu item and want to add a dynamic number of MenuItems inside it.

The number of elements depends on the network interfaces on the computer. My Mac got two interfaces, the other maybe one or three.

Creating elements is not a problem. But I want to reference the elements in later code.

-(void)addItems { NSMenuItem *menuItem = [menu addItemWithTitle:@"Start" action:@selector(click:) keyEquivalent:@""]; } 

Then I want to update the title of the element:

 -(IBAction)click:(id)sender { [menuItem setTitle:@"Clicked!"]; } 

Due to the reason, the click action returns an undeclared identifier (menuItem). The problem is that I cannot declare them in the header file because they are dynamic and they can probably reach a count of 100 elements, so I cannot declare as 10 elements and use them or not.

How can I deal with these situations? I hope you help me!

Congratulations, Julian

+4
source share
1 answer

Just ran into this problem, and it's pretty simple. You can manually track NSMenuItem pointers, but the easiest way is to use tags. When you create the menu item, do the following:

 item = [subMenu addItemWithTitle:@"A1" action:@selector(testing123:) keyEquivalent: @""]; [item setTag:23]; 

And then in your delegate:

 -(IBAction)testing123:(id) sender { NSMenuItem * item = (NSMenuItem*)sender; int cmdVal = [item tag]; printf("Testing123 - %d\n", cmdVal); } 

What is it. Just add 10 items and give them all the tags. Hooray!

+5
source

Source: https://habr.com/ru/post/1382130/


All Articles