Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Control+Click not triggering menuForEvent

All, So I have a subclass of NSBox and have subviews in it like a label and two imageViews. I have overridden menuForEvent: in it. However, when I click on the NSBox to select it and then later Control+Click on any of its subviews then menuForEvent: is never called.

I don't understand why that is the case.

like image 965
user598789 Avatar asked Aug 20 '11 00:08

user598789


2 Answers

There is a difference in how control-clicks and right-clicks are handled by NSView (as jfewtr pointed out). Contextual menus will appear for a right-click if the click falls within a subview, but not for a control-click.

I was surprised by this and actually wrote a post about it with more details here: NSView control-click quirks

There are a couple potential solutions, but overriding/customizing your entire subview tree is probably not the best choice. I've found the best fix for this is to display your contextual menu explicitly in your top-level view (your NSBox subclass) for a control-click:

- (void)mouseDown:(NSEvent *)theEvent
{
    if (theEvent.modifierFlags & NSControlKeyMask)
    {
        [NSMenu popUpContextMenu:[self menuForEvent:theEvent] withEvent:theEvent forView:self];
    }
}

While it's not great to hardcode this behavior, it avoids manipulating or traversing your entire subview tree, which can incur more problematic side effects/bugs.

like image 172
Matt R Avatar answered Sep 20 '22 07:09

Matt R


You need to implement menuForEvent: in the subviews too, and forward the event to your superview's (NSBox subclass) implementation of menuForEvent:

- (NSMenu *)menuForEvent:(NSEvent *)event
{
    return [[self superview] menuForEvent:event];
}

I assumed that it would automatically fall through to the superview without the need for subclassing the subviews. I found that a right-click does, but, for some reason, a control-click does not.

like image 40
jfewtr Avatar answered Sep 22 '22 07:09

jfewtr