自定义NSButton实现右键菜单

最终实现效果.

左键为普通按钮,右键会弹出一个菜单

自定义NSButton实现右键菜单_第1张图片
3208767-70ffaade12081774.png

实现方法

1, 重写NSButton

 -(void)rightMouseDown:(NSEvent *)theEvent{

//新建菜单
    NSMenu* newMenu = [[NSMenu allocWithZone:NSDefaultMallocZone()] initWithTitle:@"Name"];
    NSMenuItem* newItem = [[NSMenuItem alloc]init];

//设置菜单内容
    NSRect frameRect = NSMakeRect(0, 0, 200, 80);
    NSView *boundView = [[NSView alloc]initWithFrame:frameRect];

    NSRect frameTitle1 = NSMakeRect(2, 58, 30, 20);
    NSTextField *title1 = [[NSTextField alloc]initWithFrame:frameTitle1];
    title1.backgroundColor = [NSColor windowBackgroundColor];
    title1.stringValue = @"Title";
    title1.enabled = NO;
    title1.bordered = NO;
    NSRect frameText1 = NSMakeRect(32, 58, 160, 20);
    NSTextField *Text1 = [[NSTextField alloc]initWithFrame:frameText1];
   Text1.stringValue = self.title;

    NSRect frameTitle2 = NSMakeRect(2, 36, 35, 20);
    NSTextField *title2 = [[NSTextField alloc]initWithFrame:frameTitle2];
    title2.backgroundColor = [NSColor windowBackgroundColor];
    title2.stringValue = @"CMD";
    title2.enabled = NO;
    title2.bordered = NO;
    NSRect frameText2 = NSMakeRect(32, 36, 160, 20);
    NSTextField *Text2 = [[NSTextField alloc]initWithFrame:frameText2];
    Text2.stringValue = self.alternateTitle;

    NSRect frameCancel = NSMakeRect(30, 10, 60, 20);
    NSButton *cancle = [[NSButton alloc]initWithFrame:frameCancel];
//    [cancle setBordered:NO];
    [cancle setAction:@selector(cancleButton:)];
    [cancle setBezelStyle:NSBezelStyleRounded];
    cancle.title = @"取消";
    NSRect frameOK = NSMakeRect(100, 10, 60, 20);
    NSButton *OK = [[NSButton alloc]initWithFrame:frameOK];
//    [OK setBordered:NO];
  [OK setBezelStyle:NSBezelStyleRounded];
 OK.title = @"保存";
 [OK setAction:@selector(OKButton:)];
//    [OK setKeyEquivalent:@"/r"];
 [boundView addSubview:title1];
[boundView addSubview:Text1];
[boundView addSubview:title2];
[boundView addSubview:Text2];
[boundView addSubview:cancle];
[boundView addSubview:OK];

[MenuItemAry removeAllObjects];
[MenuItemAry addObjectsFromArray:@[newMenu,Text1,Text2]];
[newItem setView:boundView];

[newItem setEnabled:YES];
[newItem setTarget:self];
[newMenu addItem:newItem];

//设置菜单响应委托
 [NSMenu popUpContextMenu:newMenu withEvent:theEvent forView:self];
}

实现菜单中按键响应

 -(void)cancleButton:(id)cancle{
     NSMenu *aa = MenuItemAry[0];
    [aa cancelTracking];
}

-(void)OKButton:(id)ok{
    NSTextField *Title = MenuItemAry[1];
    NSTextField *Text = MenuItemAry[2];
    self.title = Title.stringValue;
    self.alternateTitle = Text.stringValue;
    NSLog(@"%@",self.alternateTitle);
    NSMenu *aa = MenuItemAry[0];
    [aa cancelTracking];
}

2, 拖入NSButton控件

3,选择Class为自定义类

自定义NSButton实现右键菜单_第2张图片
屏幕快照 2017-01-24 上午9.31.44.png

你可能感兴趣的:(自定义NSButton实现右键菜单)