如何向 NSMenuItem 添加复选标记

问题描述 投票:0回答:5

在上下文菜单中,如何给 NSMenuItem 打勾?我想将其放置在特定项目旁边。我在

mouseDown:
函数中创建菜单,如下图:

-(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];        
}   
}

如何给项目打勾?

cocoa menu
5个回答
21
投票

查看

NSUserInterfaceItemValidations
协议。当显示菜单时,它将使用
validateUserInterfaceItem:
方法查询响应者链中的每个响应者,以确定是否应启用该项目。 (只要链中的一个响应者返回
YES
,项目就会被启用)这也为您提供了自定义项目的机会。例如:

- (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:NSControlStateValueOn];
    }
    return YES;
}

11
投票

你想要这样的东西:

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

您可以使用 NSOffState 删除复选标记。


7
投票

使用

NSMenuValidation
协议,您可以执行以下操作:

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

    return YES;
}

5
投票

我相信 NSOnState 已被弃用(首先在 macOS 10.14 中弃用),您可以使用

NSControlStateValueOn
代替。例如:

[myItem setState: NSControlStateValueOn];

欲了解更多信息请查看这里


5
投票

在 Swift 中,你可以像这样检查

NSMenuItem

let myItem: NSMenuItem = ...
myItem.state = .on

有关更多信息,请检查https://developer.apple.com/documentation/appkit/nscontrol/statevalue

© www.soinside.com 2019 - 2024. All rights reserved.