简体   繁体   English

NSMenuItem没有启用?

[英]NSMenuItem not being enabled?

I have an NSMenuItem called history which resides in a NSMenu called menu. 我有一个名为history的NSMenuItem,它位于一个名为菜单的NSMenu中。 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. 我尝试过setEnabled但不起作用。 Please help. 请帮忙。 Here my code: 这是我的代码:

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. 请帮助,我一直试图弄清楚最后2个小时。 Thanks. 谢谢。

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 documentation on how menu items get enabled. 以下是有关如何启用菜单项的文档

I had to override the validateMenuItem method 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM