macOS-NSMenu
1 简述
管理应用菜单的对象,通常会在程序的主菜单栏,视图右键菜单,Dock菜单使用。
@interface NSMenu : NSObject <NSCopying, NSCoding, NSUserInterfaceItemIdentification, NSAccessibilityElement, NSAccessibility> |
2 NSMenu
源码注解
2.1 创建
- (instancetype)initWithTitle:(NSString *)title NS_DESIGNATED_INITIALIZER; |
2.2 常用属性
// 菜单标题 |
2.3 常用函数
// 菜单栏是否可见,visible = NO 隐藏 |
3 NSMenuItem
源码注解
@interface NSMenuItem : NSObject <NSCopying, NSCoding, NSValidatedUserInterfaceItem, NSUserInterfaceItemIdentification, NSAccessibilityElement, NSAccessibility> |
4 实际应用
Main Menu
使用
StoryBoard
添加Menu比较方便添加和删除右键Menu
在
NSView
上添加Menu- (void)viewDidLoad {
[super viewDidLoad];
NSMenu *menu = [[NSMenu alloc] initWithTitle:@"view menu"];
NSMenuItem *item1 = [[NSMenuItem alloc] initWithTitle:@"item 1" action:@selector(menuClick) keyEquivalent:@""];
item1.target = self;
NSMenuItem *item2 = [[NSMenuItem alloc] initWithTitle:@"item 2" action:@selector(menuClick) keyEquivalent:@""];
item2.target = self;
[menu addItem:item1];
[menu addItem:item2];
// 添加二级菜单
NSMenu *menu2 = [[NSMenu alloc] initWithTitle:@"sub menu"];
NSMenuItem *itemA = [[NSMenuItem alloc] initWithTitle:@"itemA" action:@selector(menuClick) keyEquivalent:@""];
itemA.target = self;
NSMenuItem *itemB = [[NSMenuItem alloc] initWithTitle:@"itemB" action:@selector(menuClick) keyEquivalent:@""];
itemB.target = self;
[menu2 addItem:itemA];
[menu2 addItem:itemB];
// 二级菜单放在指定item上
[menu setSubmenu:menu2 forItem:item2];
self.view.menu = menu;
}
- (void)menuClick {
}Dock菜单
在AppDelegate中重写
applicationDockMenu
方法- (NSMenu *)applicationDockMenu:(NSApplication *)sender {
NSMenu *menu = [[NSMenu alloc] initWithTitle:@"dock menu"];
NSMenuItem *item1 = [[NSMenuItem alloc] initWithTitle:@"item 1" action:@selector(menuClick) keyEquivalent:@""];
item1.target = self;
NSMenuItem *item2 = [[NSMenuItem alloc] initWithTitle:@"item 2" action:@selector(menuClick) keyEquivalent:@""];
item2.target = self;
[menu addItem:item1];
[menu addItem:item2];
// 添加二级菜单
NSMenu *menu2 = [[NSMenu alloc] initWithTitle:@"sub menu"];
NSMenuItem *itemA = [[NSMenuItem alloc] initWithTitle:@"itemA" action:@selector(menuClick) keyEquivalent:@""];
itemA.target = self;
NSMenuItem *itemB = [[NSMenuItem alloc] initWithTitle:@"itemB" action:@selector(menuClick) keyEquivalent:@""];
itemB.target = self;
[menu2 addItem:itemA];
[menu2 addItem:itemB];
// 二级菜单放在指定item上
[menu setSubmenu:menu2 forItem:item2];
return menu;
}