B. Nadolson
B. Nadolson

Reputation: 3038

Dynamic menus in Objective C / Cocoa

How can a dynamically add (at run-time) menu items in Objective C at run-time? An example would be to add 5 menu items for recent files.

A) How would the add menu item look?

B) How would I setup checking to see what menu item was clicked and get the index or identity?

Please don't suggest a non-dynamic solution like adding slots and hiding at run-time. I'm trying to figure out how to dynamically add menu items at run-time, which on some other platforms is rather trivial to do and I'm hoping to make that code work nicely on a Mac.

Add: Adding a menu item seems straightforward

NSMenuItem *item = [myMenu insertItemWithTitle:[NSString stringWithFormat:@"%blah"]];

But how does one get the event for a dynamically added menu item?

Upvotes: 1

Views: 1237

Answers (1)

ChenSmile
ChenSmile

Reputation: 3441

When u r adding item set a Tag for each item and pass action.

Check it-

 item = [myMenu addItemWithTitle:@"" action:@selector(HitMe:) keyEquivalent: @""];
[item setTag:10];

In Delegate-

-(void)HitMe:(id) sender{
    NSMenuItem * item = (NSMenuItem*)sender;
    int val1 = [item tag];
    printf("Value1==>%d", val1);
}

Upvotes: 1

Related Questions