NSMenuItem中的自定义视图禁用NSPopUpButton选择

paj*_*vic 3 cocoa objective-c nsview nsmenuitem nspopupbutton

我想自定义一个,NSPopUpButton所以我已经实现了一个CustomMenuItemView,现在只有以下代码(用于测试目的):

- (void)drawRect:(NSRect)dirtyRect
{
    [[NSColor redColor] set];
    NSRectFill(dirtyRect);
}
Run Code Online (Sandbox Code Playgroud)

现在,对于NSMenuItem我添加到的每一个NSMenu,myPopUpButton.menu我将视图设置为我的自定义视图:

NSMenuItem *menuItem = [[NSMenuItem alloc] initWithTitle:@"Some title" action:NULL keyEquivalent:@""];
menuItem.view = [[CustomMenuItemView alloc] initWithFrame:NSMakeRect(0, 0, 100, 25)];
Run Code Online (Sandbox Code Playgroud)

当我运行我的程序并打开弹出按钮时,菜单项选择似乎被禁用(即当我点击它时没有任何反应).

我猜它实际上并没有被禁用; 它只是不再响应事件了.我是否需要在自定义视图中添加一些事件处理?如果是这样,怎么样?

paj*_*vic 9

我通过mouseUp向我添加方法解决了这个问题CustomMenuItemView:

- (void)mouseUp:(NSEvent*) event
{
    NSMenu *menu = self.enclosingMenuItem.menu;
    [menu cancelTracking];
    [menu performActionForItemAtIndex:[menu indexOfItem:self.enclosingMenuItem]];
}
Run Code Online (Sandbox Code Playgroud)