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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With