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?
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;
}
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.
Using the NSMenuValidation
protocol you can do this:
-(BOOL)validateMenuItem:(NSMenuItem *)menuItem
{
if(menuItem.action==@selector(actionMethodForItemThatShouldBeChecked:))
{
menuItem.state=NSOnState;
}
return YES;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With