NSMenuItem中的鼠标事件使用子菜单查看

时间:2014-01-10 16:59:29

标签: objective-c xcode macos cocoa nsmenu

按钮点击后弹出菜单。

将一些项目添加到菜单并制作第一个项目子菜单。

我想在所有项目中处理“选择事件”,并且使用标准菜单一切都很好。 但是当我尝试在NSMenuItem上创建自定义View时,子菜单失去了将事件发送到动作选择器的能力,并且自定义NSView无法处理mouseUp和mouseDown事件。

这里我的代码全部清晰

#import "CRGAppDelegate.h"
@interface customItemView : NSView
{
    NSTrackingArea *_trackArea;
}
@end

@implementation customItemView

-(void)drawRect:(NSRect)dirtyRect{
    [[NSColor redColor] set];
    [[NSBezierPath bezierPathWithRect:NSMakeRect(0, 0, 1, 100)] fill];
    NSString* str = self.enclosingMenuItem.title;
    [str drawInRect:NSMakeRect(10, 4, 80, 22) withAttributes:nil];
}

-(void)mouseDown:(NSEvent *)theEvent
{
    NSLog(@"Mouse Down");
}
-(void)mouseUp:(NSEvent *)theEvent
{
    NSLog(@"Mouse Up");
}

-(void)updateTrackingAreas
{
    [self removeTrackingArea:_trackArea];
    _trackArea = [[NSTrackingArea alloc] initWithRect:[self bounds] options:(NSTrackingMouseEnteredAndExited |
                                                                             NSTrackingActiveAlways |
                                                                             NSTrackingEnabledDuringMouseDrag
                                                                             ) owner:self userInfo:nil];
    [self addTrackingArea:_trackArea];
}
@end

@implementation CRGAppDelegate
{
    NSMenu* mainMenu;

}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    // Insert code here to initialize your application
    mainMenu = [[NSMenu alloc] initWithTitle:@"mainMenu"];

    for (int i = 0; i < 10; ++i)
    {
        NSMenuItem* item = [[NSMenuItem alloc] initWithTitle:@"title"
                                                      action:@selector(firstLevelItems:)
                                               keyEquivalent:@""];
        [item setView:[[customItemView alloc] initWithFrame:NSMakeRect(0, 0, 100, 30)]];
        [mainMenu addItem:item];

        if (i == 0)
        {
            //add submenu
            NSMenu* submenu = [[NSMenu alloc] initWithTitle:@"Submenu"];
            [item setSubmenu:submenu];
            for (int j = 0; j < 5; ++j)
            {
                NSMenuItem* submenuItem = [[NSMenuItem alloc] initWithTitle:@"submenuitem"
                                                                     action:@selector(secondLevelItems:)
                                                              keyEquivalent:@""];
                [submenu addItem:submenuItem];
            }
        }
    }
}

-(void)secondLevelItems:(id)sender
{
    NSLog(@"%@",sender);
}

-(void)firstLevelItems:(id)sender
{
    NSLog(@"%@",sender);
}

- (IBAction)ExpandMenuAction:(id)sender {
    [mainMenu popUpMenuPositioningItem:nil atLocation:NSMakePoint(0, 35) inView:_OpenMenuButton];
}
@end

在这种情况下,我如何收到选择事件?

0 个答案:

没有答案