Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a check mark to an NSMenuItem

Tags:

cocoa

menu

In a contextual menu, how can I give an NSMenuItem a check mark? I want to place it next to specific items. I create the menu in the mouseDown: function, as shown below:

-(void)mouseDown:(NSEvent *)event
{
NSPoint pointInView = [self convertPoint:[event locationInWindow] fromView:nil];

if (NSPointInRect(pointInView, [self shapeRect]) )
{       
    NSMenu *theMenu = [[[NSMenu alloc] initWithTitle:@"default Contextual Menu"] autorelease];

    [theMenu insertItemWithTitle:@"Circle" action:@selector(circle:) keyEquivalent:@"" atIndex:0];
    [theMenu insertItemWithTitle:@"Rectangle" action:@selector(rectangle:) keyEquivalent:@"" atIndex:1];

    [NSMenu popUpContextMenu:theMenu withEvent:event forView:self];        
}   
}

How can I give the items a check mark?

like image 934
sateesh Avatar asked Feb 01 '10 12:02

sateesh


3 Answers

Take a look at the NSUserInterfaceItemValidations protocol. When a menu is displayed, it will query each responder in the responder chain with validateUserInterfaceItem: method to determine if the item should be enabled. (An item will be enabled so long as one responder in the chain returns YES) This also gives you an opportunity to customize the item. For example:

- (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item {
    if ([item action] == @selector(actionMethodForItemThatShouldBeChecked:)] {
        // This method is also used for toolbar items, so it's a good idea to 
        // make sure you're validating a menu item here
        if ([item respondsToSelector:@selector(setState:)])
            [item setState:NSOnState];
    }
    return YES;
}
like image 116
Alex Avatar answered Oct 14 '22 10:10

Alex


You want something like this:

// Place a check mark next to "Circle"
NSMenuItem * theItem = [theMenu indexOfItemWithTitle: @"Circle"];
[item setState: NSOnState];

You would use NSOffState to remove the check mark.

like image 29
Daniel Jette Avatar answered Oct 14 '22 08:10

Daniel Jette


Using the NSMenuValidation protocol you can do this:

-(BOOL)validateMenuItem:(NSMenuItem *)menuItem
{
    if(menuItem.action==@selector(actionMethodForItemThatShouldBeChecked:))
    {
        menuItem.state=NSOnState;
    }

    return YES;
}
like image 5
DavidA Avatar answered Oct 14 '22 08:10

DavidA