以编程方式创建带有 NSMenuItems 的 NSMenu? [英] Creating NSMenu with NSMenuItems in it, programmatically?

查看:17
本文介绍了以编程方式创建带有 NSMenuItems 的 NSMenu?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我想指出这个问题可能已经有人问过了,我只是从他们那里找不到任何答案.

First, I'd like to point out that this question is probably already asked, I just couldn't find any answers from them.

所以,我正在以编程方式尝试为主栏创建一个 NSMenu 和 NSMenuItem,所以 fe.NSMenu 将是文件,然后它会有 3 个 NSMenuItem,新建、打开和保存.

So, I'm programmatically trying to create a NSMenu and NSMenuItem to the main bar, so fe. NSMenu would be File and then it would have 3x NSMenuItem in it, New, Open and Save.

但没有任何效果,这是我目前所拥有的:

But nothing's working, here's what I have currently:

NSMenu *fileMenu = [[NSMenu alloc] initWithTitle:@"File"];
NSMenuItem *newMenu = [[NSMenuItem alloc] initWithTitle:@"New" action:NULL keyEquivalent:@""];
NSMenuItem *openMenu = [[NSMenuItem alloc] initWithTitle:@"Open" action:NULL keyEquivalent:@""];
NSMenuItem *saveMenu = [[NSMenuItem alloc] initWithTitle:@"Save" action:NULL keyEquivalent:@""];
[newMenu setMenu:fileMenu];
[openMenu setMenu:fileMenu];
[saveMenu setMenu:fileMenu];

但是什么也没发生,我很确定我必须告诉应用程序它应该使用fileMenu,但是我该怎么做,如果这不是问题,那是什么?我对这些东西很陌生,但对学习很感兴趣,所以有任何提示都比没有好!

But nothing happens, I'm pretty sure I have to tell the application that it should use fileMenu, but how do I do that, and if that's not the problem, then what is? I'm pretty new at this stuff, but interested in learning, so just any tip will be better than nothing!

推荐答案

设置菜单时,您设置的是为该项目显示的菜单,而不是其父菜单.

When you set the menu, you set the menu that appears for that item, not its parent menu.

要将这三个项目添加到您的菜单中,请使用:

To add those three items to your menu, use:

[fileMenu addItem: newMenu];
[fileMenu addItem: openMenu];
[fileMenu addItem: saveMenu];

然后将菜单添加到菜单栏:

And then to add the menu to the menu bar:

NSMenuItem *fileMenuItem = [[NSMenuItem alloc] initWithTitle: @"File"];
[fileMenuItem setSubmenu: fileMenu]; // was setMenu:
[[NSApp mainMenu] addItem: fileMenuItem];
[fileMenuItem release];

每个菜单都拥有多个菜单项;单个菜单项可以负责一个子菜单;所有这些菜单都通过 [NSApp mainMenu] 锚定到 UI.

Every menu owns multiple menu items; a single menu item can be responsible for a submenu; and all these menus are anchored to the UI by [NSApp mainMenu].

这篇关于以编程方式创建带有 NSMenuItems 的 NSMenu?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆