在想要显示菜单的视图文件中添加如下代码:
-(void)rightMouseDown:(NSEvent *)event{
//创建Menu
NSMenu *theMenu = [[NSMenualloc] initWithTitle:@"Contextual Menu"];
//自定义的NSMenuItem
NSMenuItem *item3 = [[NSMenuItemalloc]init];
self.customView.wantsLayer =YES;
self.customView.layer.backgroundColor = [NSColorredColor].CGColor;
item3.title = @"Item 3";
item3.view = self.customView;
item3.target = self;
item3.action = @selector(beep:);
[theMenu insertItemWithTitle:@"Item 1"action:@selector(beep:)keyEquivalent:@""atIndex:0];
[theMenu insertItemWithTitle:@"Item 2"action:@selector(beep:)keyEquivalent:@""atIndex:1];
[theMenu insertItem:item3 atIndex:2];
[NSMenu popUpContextMenu:theMenuwithEvent:event forView:self.view];
}
-(void)beep:(NSMenuItem *)menuItem{
NSLog(@"_____%@", menuItem);
}
- (void)setRepresentedObject:(id)representedObject {
[super setRepresentedObject:representedObject];
// Update the view, if already loaded.
}