xcode NSMenuItem 没有被启用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5124249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 20:19:45  来源:igfitidea点击:

NSMenuItem not being enabled?

objective-ccocoaxcodensmenuitem

提问by user635064

I have an NSMenuItem called history which resides in a NSMenu called menu. When my program starts history doesn't have a submenu so its disabled. Then at some point, I need a submenu for history, so I create it, make it a submenu of history. An arrow appears beside history which tells me that the submenu is there. But history is still disabled. I have tried setEnabled but doesn't work. Please help. Here my code:

我有一个名为 history 的 NSMenuItem,它驻留在名为 menu 的 NSMenu 中。当我的程序启动历史没有子菜单时,它被禁用。然后在某个时候,我需要一个历史的子菜单,所以我创建了它,使它成为历史的子菜单。历史记录旁边会出现一个箭头,告诉我子菜单在那里。但是历史仍然是禁用的。我试过 setEnabled 但不起作用。请帮忙。这是我的代码:

This is when I create my menu, and history as you can see an NSMenuItem in menu.

这是我创建菜单和历史的时候,你可以在菜单中看到一个 NSMenuItem。

    menu = [[NSMenu alloc] initWithTitle:@"Menu"];
[[menu addItemWithTitle:@"History" action:nil keyEquivalent:@""] setTarget:self];
[[menu addItemWithTitle:@"Settings" action:@selector(loadSettings:) keyEquivalent:@""] setTarget:self];
[[menu addItemWithTitle:@"Quit" action:@selector(terminateApp:) keyEquivalent:@""] setTarget:self];

At this point, history is disabled (greyed out). Then somewhere in the program I need to have a submenu for history so:

此时,历史记录被禁用(变灰)。然后在程序的某个地方我需要有一个历史子菜单,所以:

        if (historyMenu == nil) {
        historyMenu = [[NSMenu alloc] initWithTitle:@"Lyrics history"];
        [menu setSubmenu:historyMenu forItem:[menu itemWithTitle:@"History"]];
    }

I now see an arrow beside history, but it's still greyed out.

我现在在历史旁边看到一个箭头,但它仍然是灰色的。

Please help, I have been trying to figure this out for last 2 hours. Thanks.

请帮忙,我过去 2 小时一直在努力解决这个问题。谢谢。

回答by Jon Steinmetz

You are setting the target but have a nil action. Try not setting the target. This may leave it enabled all the time in which case you may have to manually enable or disable the menu item.

您正在设置目标但没有操作。尽量不要设定目标。这可能会一直启用它,在这种情况下,您可能必须手动启用或禁用菜单项。

Here is the documentationon how menu items get enabled.

这是有关如何启用菜单项的文档

回答by Adam Johns

I had to override the validateMenuItemmethod to return true:

我不得不将该validateMenuItem方法覆盖为return true

override func validateMenuItem(menuItem: NSMenuItem) -> Bool {
    return true
}

It didn't actually use the validation method until I set target to self though like you did with

它实际上并没有使用验证方法,直到我将目标设置为 self 虽然像你一样

menu.addItemWithTitle("An Item", action: #selector(itemPressed), keyEquivalent: "")?.target = self